babylon.2.1-beta.debug.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964
  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 () { return new Color3(1, 0, 0); };
  106. Color3.Green = function () { return new Color3(0, 1, 0); };
  107. Color3.Blue = function () { return new Color3(0, 0, 1); };
  108. Color3.Black = function () { return new Color3(0, 0, 0); };
  109. Color3.White = function () { return new Color3(1, 1, 1); };
  110. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  111. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  112. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  113. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  114. return Color3;
  115. })();
  116. BABYLON.Color3 = Color3;
  117. var Color4 = (function () {
  118. function Color4(r, g, b, a) {
  119. this.r = r;
  120. this.g = g;
  121. this.b = b;
  122. this.a = a;
  123. }
  124. // Operators
  125. Color4.prototype.addInPlace = function (right) {
  126. this.r += right.r;
  127. this.g += right.g;
  128. this.b += right.b;
  129. this.a += right.a;
  130. return this;
  131. };
  132. Color4.prototype.asArray = function () {
  133. var result = [];
  134. this.toArray(result, 0);
  135. return result;
  136. };
  137. Color4.prototype.toArray = function (array, index) {
  138. if (index === undefined) {
  139. index = 0;
  140. }
  141. array[index] = this.r;
  142. array[index + 1] = this.g;
  143. array[index + 2] = this.b;
  144. array[index + 3] = this.a;
  145. return this;
  146. };
  147. Color4.prototype.add = function (right) {
  148. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  149. };
  150. Color4.prototype.subtract = function (right) {
  151. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  152. };
  153. Color4.prototype.subtractToRef = function (right, result) {
  154. result.r = this.r - right.r;
  155. result.g = this.g - right.g;
  156. result.b = this.b - right.b;
  157. result.a = this.a - right.a;
  158. return this;
  159. };
  160. Color4.prototype.scale = function (scale) {
  161. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  162. };
  163. Color4.prototype.scaleToRef = function (scale, result) {
  164. result.r = this.r * scale;
  165. result.g = this.g * scale;
  166. result.b = this.b * scale;
  167. result.a = this.a * scale;
  168. return this;
  169. };
  170. Color4.prototype.toString = function () {
  171. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  172. };
  173. Color4.prototype.clone = function () {
  174. return new Color4(this.r, this.g, this.b, this.a);
  175. };
  176. Color4.prototype.copyFrom = function (source) {
  177. this.r = source.r;
  178. this.g = source.g;
  179. this.b = source.b;
  180. this.a = source.a;
  181. return this;
  182. };
  183. // Statics
  184. Color4.Lerp = function (left, right, amount) {
  185. var result = new Color4(0, 0, 0, 0);
  186. Color4.LerpToRef(left, right, amount, result);
  187. return result;
  188. };
  189. Color4.LerpToRef = function (left, right, amount, result) {
  190. result.r = left.r + (right.r - left.r) * amount;
  191. result.g = left.g + (right.g - left.g) * amount;
  192. result.b = left.b + (right.b - left.b) * amount;
  193. result.a = left.a + (right.a - left.a) * amount;
  194. };
  195. Color4.FromArray = function (array, offset) {
  196. if (offset === void 0) { offset = 0; }
  197. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  198. };
  199. Color4.FromInts = function (r, g, b, a) {
  200. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  201. };
  202. return Color4;
  203. })();
  204. BABYLON.Color4 = Color4;
  205. var Vector2 = (function () {
  206. function Vector2(x, y) {
  207. this.x = x;
  208. this.y = y;
  209. }
  210. Vector2.prototype.toString = function () {
  211. return "{X: " + this.x + " Y:" + this.y + "}";
  212. };
  213. // Operators
  214. Vector2.prototype.toArray = function (array, index) {
  215. if (index === void 0) { index = 0; }
  216. array[index] = this.x;
  217. array[index + 1] = this.y;
  218. return this;
  219. };
  220. Vector2.prototype.asArray = function () {
  221. var result = [];
  222. this.toArray(result, 0);
  223. return result;
  224. };
  225. Vector2.prototype.copyFrom = function (source) {
  226. this.x = source.x;
  227. this.y = source.y;
  228. return this;
  229. };
  230. Vector2.prototype.copyFromFloats = function (x, y) {
  231. this.x = x;
  232. this.y = y;
  233. return this;
  234. };
  235. Vector2.prototype.add = function (otherVector) {
  236. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  237. };
  238. Vector2.prototype.addVector3 = function (otherVector) {
  239. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  240. };
  241. Vector2.prototype.subtract = function (otherVector) {
  242. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  243. };
  244. Vector2.prototype.subtractInPlace = function (otherVector) {
  245. this.x -= otherVector.x;
  246. this.y -= otherVector.y;
  247. return this;
  248. };
  249. Vector2.prototype.multiplyInPlace = function (otherVector) {
  250. this.x *= otherVector.x;
  251. this.y *= otherVector.y;
  252. return this;
  253. };
  254. Vector2.prototype.multiply = function (otherVector) {
  255. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  256. };
  257. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  258. result.x = this.x * otherVector.x;
  259. result.y = this.y * otherVector.y;
  260. return this;
  261. };
  262. Vector2.prototype.multiplyByFloats = function (x, y) {
  263. return new Vector2(this.x * x, this.y * y);
  264. };
  265. Vector2.prototype.divide = function (otherVector) {
  266. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  267. };
  268. Vector2.prototype.divideToRef = function (otherVector, result) {
  269. result.x = this.x / otherVector.x;
  270. result.y = this.y / otherVector.y;
  271. return this;
  272. };
  273. Vector2.prototype.negate = function () {
  274. return new Vector2(-this.x, -this.y);
  275. };
  276. Vector2.prototype.scaleInPlace = function (scale) {
  277. this.x *= scale;
  278. this.y *= scale;
  279. return this;
  280. };
  281. Vector2.prototype.scale = function (scale) {
  282. return new Vector2(this.x * scale, this.y * scale);
  283. };
  284. Vector2.prototype.equals = function (otherVector) {
  285. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  286. };
  287. Vector2.prototype.equalsWithEpsilon = function (otherVector) {
  288. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y);
  289. };
  290. // Properties
  291. Vector2.prototype.length = function () {
  292. return Math.sqrt(this.x * this.x + this.y * this.y);
  293. };
  294. Vector2.prototype.lengthSquared = function () {
  295. return (this.x * this.x + this.y * this.y);
  296. };
  297. // Methods
  298. Vector2.prototype.normalize = function () {
  299. var len = this.length();
  300. if (len === 0)
  301. return this;
  302. var num = 1.0 / len;
  303. this.x *= num;
  304. this.y *= num;
  305. return this;
  306. };
  307. Vector2.prototype.clone = function () {
  308. return new Vector2(this.x, this.y);
  309. };
  310. // Statics
  311. Vector2.Zero = function () {
  312. return new Vector2(0, 0);
  313. };
  314. Vector2.FromArray = function (array, offset) {
  315. if (offset === void 0) { offset = 0; }
  316. return new Vector2(array[offset], array[offset + 1]);
  317. };
  318. Vector2.FromArrayToRef = function (array, offset, result) {
  319. result.x = array[offset];
  320. result.y = array[offset + 1];
  321. };
  322. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  323. var squared = amount * amount;
  324. var cubed = amount * squared;
  325. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  326. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  327. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  328. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  329. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  330. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  331. return new Vector2(x, y);
  332. };
  333. Vector2.Clamp = function (value, min, max) {
  334. var x = value.x;
  335. x = (x > max.x) ? max.x : x;
  336. x = (x < min.x) ? min.x : x;
  337. var y = value.y;
  338. y = (y > max.y) ? max.y : y;
  339. y = (y < min.y) ? min.y : y;
  340. return new Vector2(x, y);
  341. };
  342. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  346. var part2 = (-2.0 * cubed) + (3.0 * squared);
  347. var part3 = (cubed - (2.0 * squared)) + amount;
  348. var part4 = cubed - squared;
  349. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  350. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  351. return new Vector2(x, y);
  352. };
  353. Vector2.Lerp = function (start, end, amount) {
  354. var x = start.x + ((end.x - start.x) * amount);
  355. var y = start.y + ((end.y - start.y) * amount);
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Dot = function (left, right) {
  359. return left.x * right.x + left.y * right.y;
  360. };
  361. Vector2.Normalize = function (vector) {
  362. var newVector = vector.clone();
  363. newVector.normalize();
  364. return newVector;
  365. };
  366. Vector2.Minimize = function (left, right) {
  367. var x = (left.x < right.x) ? left.x : right.x;
  368. var y = (left.y < right.y) ? left.y : right.y;
  369. return new Vector2(x, y);
  370. };
  371. Vector2.Maximize = function (left, right) {
  372. var x = (left.x > right.x) ? left.x : right.x;
  373. var y = (left.y > right.y) ? left.y : right.y;
  374. return new Vector2(x, y);
  375. };
  376. Vector2.Transform = function (vector, transformation) {
  377. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  378. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  379. return new Vector2(x, y);
  380. };
  381. Vector2.Distance = function (value1, value2) {
  382. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  383. };
  384. Vector2.DistanceSquared = function (value1, value2) {
  385. var x = value1.x - value2.x;
  386. var y = value1.y - value2.y;
  387. return (x * x) + (y * y);
  388. };
  389. return Vector2;
  390. })();
  391. BABYLON.Vector2 = Vector2;
  392. var Vector3 = (function () {
  393. function Vector3(x, y, z) {
  394. this.x = x;
  395. this.y = y;
  396. this.z = z;
  397. }
  398. Vector3.prototype.toString = function () {
  399. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  400. };
  401. // Operators
  402. Vector3.prototype.asArray = function () {
  403. var result = [];
  404. this.toArray(result, 0);
  405. return result;
  406. };
  407. Vector3.prototype.toArray = function (array, index) {
  408. if (index === void 0) { index = 0; }
  409. array[index] = this.x;
  410. array[index + 1] = this.y;
  411. array[index + 2] = this.z;
  412. return this;
  413. };
  414. Vector3.prototype.toQuaternion = function () {
  415. var result = new Quaternion(0, 0, 0, 1);
  416. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  417. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  418. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  419. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  420. var cosy = Math.cos(this.y * 0.5);
  421. var siny = Math.sin(this.y * 0.5);
  422. result.x = coszMinusx * siny;
  423. result.y = -sinzMinusx * siny;
  424. result.z = sinxPlusz * cosy;
  425. result.w = cosxPlusz * cosy;
  426. return result;
  427. };
  428. Vector3.prototype.addInPlace = function (otherVector) {
  429. this.x += otherVector.x;
  430. this.y += otherVector.y;
  431. this.z += otherVector.z;
  432. return this;
  433. };
  434. Vector3.prototype.add = function (otherVector) {
  435. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  436. };
  437. Vector3.prototype.addToRef = function (otherVector, result) {
  438. result.x = this.x + otherVector.x;
  439. result.y = this.y + otherVector.y;
  440. result.z = this.z + otherVector.z;
  441. return this;
  442. };
  443. Vector3.prototype.subtractInPlace = function (otherVector) {
  444. this.x -= otherVector.x;
  445. this.y -= otherVector.y;
  446. this.z -= otherVector.z;
  447. return this;
  448. };
  449. Vector3.prototype.subtract = function (otherVector) {
  450. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  451. };
  452. Vector3.prototype.subtractToRef = function (otherVector, result) {
  453. result.x = this.x - otherVector.x;
  454. result.y = this.y - otherVector.y;
  455. result.z = this.z - otherVector.z;
  456. return this;
  457. };
  458. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  459. return new Vector3(this.x - x, this.y - y, this.z - z);
  460. };
  461. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  462. result.x = this.x - x;
  463. result.y = this.y - y;
  464. result.z = this.z - z;
  465. return this;
  466. };
  467. Vector3.prototype.negate = function () {
  468. return new Vector3(-this.x, -this.y, -this.z);
  469. };
  470. Vector3.prototype.scaleInPlace = function (scale) {
  471. this.x *= scale;
  472. this.y *= scale;
  473. this.z *= scale;
  474. return this;
  475. };
  476. Vector3.prototype.scale = function (scale) {
  477. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  478. };
  479. Vector3.prototype.scaleToRef = function (scale, result) {
  480. result.x = this.x * scale;
  481. result.y = this.y * scale;
  482. result.z = this.z * scale;
  483. };
  484. Vector3.prototype.equals = function (otherVector) {
  485. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  486. };
  487. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  488. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z);
  489. };
  490. Vector3.prototype.equalsToFloats = function (x, y, z) {
  491. return this.x === x && this.y === y && this.z === z;
  492. };
  493. Vector3.prototype.multiplyInPlace = function (otherVector) {
  494. this.x *= otherVector.x;
  495. this.y *= otherVector.y;
  496. this.z *= otherVector.z;
  497. return this;
  498. };
  499. Vector3.prototype.multiply = function (otherVector) {
  500. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  501. };
  502. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  503. result.x = this.x * otherVector.x;
  504. result.y = this.y * otherVector.y;
  505. result.z = this.z * otherVector.z;
  506. return this;
  507. };
  508. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  509. return new Vector3(this.x * x, this.y * y, this.z * z);
  510. };
  511. Vector3.prototype.divide = function (otherVector) {
  512. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  513. };
  514. Vector3.prototype.divideToRef = function (otherVector, result) {
  515. result.x = this.x / otherVector.x;
  516. result.y = this.y / otherVector.y;
  517. result.z = this.z / otherVector.z;
  518. return this;
  519. };
  520. Vector3.prototype.MinimizeInPlace = function (other) {
  521. if (other.x < this.x)
  522. this.x = other.x;
  523. if (other.y < this.y)
  524. this.y = other.y;
  525. if (other.z < this.z)
  526. this.z = other.z;
  527. return this;
  528. };
  529. Vector3.prototype.MaximizeInPlace = function (other) {
  530. if (other.x > this.x)
  531. this.x = other.x;
  532. if (other.y > this.y)
  533. this.y = other.y;
  534. if (other.z > this.z)
  535. this.z = other.z;
  536. return this;
  537. };
  538. // Properties
  539. Vector3.prototype.length = function () {
  540. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  541. };
  542. Vector3.prototype.lengthSquared = function () {
  543. return (this.x * this.x + this.y * this.y + this.z * this.z);
  544. };
  545. // Methods
  546. Vector3.prototype.normalize = function () {
  547. var len = this.length();
  548. if (len === 0)
  549. return this;
  550. var num = 1.0 / len;
  551. this.x *= num;
  552. this.y *= num;
  553. this.z *= num;
  554. return this;
  555. };
  556. Vector3.prototype.clone = function () {
  557. return new Vector3(this.x, this.y, this.z);
  558. };
  559. Vector3.prototype.copyFrom = function (source) {
  560. this.x = source.x;
  561. this.y = source.y;
  562. this.z = source.z;
  563. return this;
  564. };
  565. Vector3.prototype.copyFromFloats = function (x, y, z) {
  566. this.x = x;
  567. this.y = y;
  568. this.z = z;
  569. return this;
  570. };
  571. // Statics
  572. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  573. var d0 = Vector3.Dot(vector0, axis) - size;
  574. var d1 = Vector3.Dot(vector1, axis) - size;
  575. var s = d0 / (d0 - d1);
  576. return s;
  577. };
  578. Vector3.FromArray = function (array, offset) {
  579. if (!offset) {
  580. offset = 0;
  581. }
  582. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  583. };
  584. Vector3.FromArrayToRef = function (array, offset, result) {
  585. result.x = array[offset];
  586. result.y = array[offset + 1];
  587. result.z = array[offset + 2];
  588. };
  589. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  590. result.x = array[offset];
  591. result.y = array[offset + 1];
  592. result.z = array[offset + 2];
  593. };
  594. Vector3.FromFloatsToRef = function (x, y, z, result) {
  595. result.x = x;
  596. result.y = y;
  597. result.z = z;
  598. };
  599. Vector3.Zero = function () {
  600. return new Vector3(0, 0, 0);
  601. };
  602. Vector3.Up = function () {
  603. return new Vector3(0, 1.0, 0);
  604. };
  605. Vector3.TransformCoordinates = function (vector, transformation) {
  606. var result = Vector3.Zero();
  607. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  608. return result;
  609. };
  610. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  611. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  612. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  613. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  614. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  615. result.x = x / w;
  616. result.y = y / w;
  617. result.z = z / w;
  618. };
  619. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  620. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  621. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  622. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  623. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  624. result.x = rx / rw;
  625. result.y = ry / rw;
  626. result.z = rz / rw;
  627. };
  628. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  629. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  630. var m0 = SIMD.float32x4.load(transformation.m, 0);
  631. var m1 = SIMD.float32x4.load(transformation.m, 4);
  632. var m2 = SIMD.float32x4.load(transformation.m, 8);
  633. var m3 = SIMD.float32x4.load(transformation.m, 12);
  634. 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));
  635. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  636. SIMD.float32x4.storeXYZ(result._data, 0, r);
  637. };
  638. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  639. var v0 = SIMD.float32x4.splat(x);
  640. var v1 = SIMD.float32x4.splat(y);
  641. var v2 = SIMD.float32x4.splat(z);
  642. var m0 = SIMD.float32x4.load(transformation.m, 0);
  643. var m1 = SIMD.float32x4.load(transformation.m, 4);
  644. var m2 = SIMD.float32x4.load(transformation.m, 8);
  645. var m3 = SIMD.float32x4.load(transformation.m, 12);
  646. 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));
  647. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  648. SIMD.float32x4.storeXYZ(result._data, 0, r);
  649. };
  650. Vector3.TransformNormal = function (vector, transformation) {
  651. var result = Vector3.Zero();
  652. Vector3.TransformNormalToRef(vector, transformation, result);
  653. return result;
  654. };
  655. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  656. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  657. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  658. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  659. };
  660. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  661. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  662. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  663. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  664. };
  665. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  666. var squared = amount * amount;
  667. var cubed = amount * squared;
  668. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  669. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  670. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  671. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  672. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  673. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  674. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  675. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  676. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  677. return new Vector3(x, y, z);
  678. };
  679. Vector3.Clamp = function (value, min, max) {
  680. var x = value.x;
  681. x = (x > max.x) ? max.x : x;
  682. x = (x < min.x) ? min.x : x;
  683. var y = value.y;
  684. y = (y > max.y) ? max.y : y;
  685. y = (y < min.y) ? min.y : y;
  686. var z = value.z;
  687. z = (z > max.z) ? max.z : z;
  688. z = (z < min.z) ? min.z : z;
  689. return new Vector3(x, y, z);
  690. };
  691. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  692. var squared = amount * amount;
  693. var cubed = amount * squared;
  694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  696. var part3 = (cubed - (2.0 * squared)) + amount;
  697. var part4 = cubed - squared;
  698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  701. return new Vector3(x, y, z);
  702. };
  703. Vector3.Lerp = function (start, end, amount) {
  704. var x = start.x + ((end.x - start.x) * amount);
  705. var y = start.y + ((end.y - start.y) * amount);
  706. var z = start.z + ((end.z - start.z) * amount);
  707. return new Vector3(x, y, z);
  708. };
  709. Vector3.Dot = function (left, right) {
  710. return (left.x * right.x + left.y * right.y + left.z * right.z);
  711. };
  712. Vector3.Cross = function (left, right) {
  713. var result = Vector3.Zero();
  714. Vector3.CrossToRef(left, right, result);
  715. return result;
  716. };
  717. Vector3.CrossToRef = function (left, right, result) {
  718. result.x = left.y * right.z - left.z * right.y;
  719. result.y = left.z * right.x - left.x * right.z;
  720. result.z = left.x * right.y - left.y * right.x;
  721. };
  722. Vector3.Normalize = function (vector) {
  723. var result = Vector3.Zero();
  724. Vector3.NormalizeToRef(vector, result);
  725. return result;
  726. };
  727. Vector3.NormalizeToRef = function (vector, result) {
  728. result.copyFrom(vector);
  729. result.normalize();
  730. };
  731. Vector3.Project = function (vector, world, transform, viewport) {
  732. var cw = viewport.width;
  733. var ch = viewport.height;
  734. var cx = viewport.x;
  735. var cy = viewport.y;
  736. 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);
  737. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  738. return Vector3.TransformCoordinates(vector, finalMatrix);
  739. };
  740. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  741. var matrix = world.multiply(transform);
  742. matrix.invert();
  743. source.x = source.x / viewportWidth * 2 - 1;
  744. source.y = -(source.y / viewportHeight * 2 - 1);
  745. var vector = Vector3.TransformCoordinates(source, matrix);
  746. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  747. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  748. vector = vector.scale(1.0 / num);
  749. }
  750. return vector;
  751. };
  752. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  753. var matrix = world.multiply(view).multiply(projection);
  754. matrix.invert();
  755. source.x = source.x / viewportWidth * 2 - 1;
  756. source.y = -(source.y / viewportHeight * 2 - 1);
  757. var vector = Vector3.TransformCoordinates(source, matrix);
  758. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  759. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  760. vector = vector.scale(1.0 / num);
  761. }
  762. return vector;
  763. };
  764. Vector3.Minimize = function (left, right) {
  765. var min = left.clone();
  766. min.MinimizeInPlace(right);
  767. return min;
  768. };
  769. Vector3.Maximize = function (left, right) {
  770. var max = left.clone();
  771. max.MaximizeInPlace(right);
  772. return max;
  773. };
  774. Vector3.Distance = function (value1, value2) {
  775. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  776. };
  777. Vector3.DistanceSquared = function (value1, value2) {
  778. var x = value1.x - value2.x;
  779. var y = value1.y - value2.y;
  780. var z = value1.z - value2.z;
  781. return (x * x) + (y * y) + (z * z);
  782. };
  783. Vector3.Center = function (value1, value2) {
  784. var center = value1.add(value2);
  785. center.scaleInPlace(0.5);
  786. return center;
  787. };
  788. /**
  789. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  790. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  791. * to something in order to rotate it from its local system to the given target system.
  792. */
  793. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  794. var u = Vector3.Normalize(axis1);
  795. var v = Vector3.Normalize(axis2);
  796. var w = Vector3.Normalize(axis3);
  797. // world axis
  798. var X = Axis.X;
  799. var Y = Axis.Y;
  800. var Z = Axis.Z;
  801. // equation unknowns and vars
  802. var yaw = 0.0;
  803. var pitch = 0.0;
  804. var roll = 0.0;
  805. var x = 0.0;
  806. var y = 0.0;
  807. var z = 0.0;
  808. var t = 0.0;
  809. var sign = -1.0;
  810. var pi = Math.PI;
  811. var nbRevert = 0;
  812. var cross;
  813. var dot = 0.0;
  814. // step 1 : rotation around w
  815. // Rv3(u) = u1, and u1 belongs to plane xOz
  816. // Rv3(w) = w1 = w invariant
  817. var u1;
  818. var v1;
  819. if (w.z == 0) {
  820. z = 1.0;
  821. }
  822. else if (w.x == 0) {
  823. x = 1.0;
  824. }
  825. else {
  826. t = w.z / w.x;
  827. x = -t * Math.sqrt(1 / (1 + t * t));
  828. z = Math.sqrt(1 / (1 + t * t));
  829. }
  830. u1 = new Vector3(x, y, z);
  831. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  832. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  833. if (Vector3.Dot(w, cross) < 0) {
  834. sign = 1;
  835. }
  836. dot = Vector3.Dot(u, u1);
  837. roll = Math.acos(dot) * sign;
  838. if (Vector3.Dot(u1, X) < 0) {
  839. roll = Math.PI + roll;
  840. u1 = u1.scaleInPlace(-1);
  841. v1 = v1.scaleInPlace(-1);
  842. nbRevert++;
  843. }
  844. // step 2 : rotate around u1
  845. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  846. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  847. var w2;
  848. var v2;
  849. x = 0.0;
  850. y = 0.0;
  851. z = 0.0;
  852. sign = -1;
  853. if (w.z == 0) {
  854. x = 1.0;
  855. }
  856. else {
  857. t = u1.z / u1.x;
  858. x = -t * Math.sqrt(1 / (1 + t * t));
  859. z = Math.sqrt(1 / (1 + t * t));
  860. }
  861. w2 = new BABYLON.Vector3(x, y, z);
  862. v2 = BABYLON.Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  863. cross = BABYLON.Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  864. if (BABYLON.Vector3.Dot(u1, cross) < 0) {
  865. sign = 1;
  866. }
  867. dot = BABYLON.Vector3.Dot(w, w2);
  868. pitch = Math.acos(dot) * sign;
  869. if (BABYLON.Vector3.Dot(v2, Y) < 0) {
  870. pitch = Math.PI + pitch;
  871. v2 = v2.scaleInPlace(-1);
  872. w2 = w2.scaleInPlace(-1);
  873. nbRevert++;
  874. }
  875. // step 3 : rotate around v2
  876. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  877. sign = -1;
  878. cross = BABYLON.Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  879. if (BABYLON.Vector3.Dot(cross, Y) < 0) {
  880. sign = 1;
  881. }
  882. dot = BABYLON.Vector3.Dot(u1, X);
  883. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  884. if (dot < 0 && nbRevert < 2) {
  885. yaw = Math.PI + yaw;
  886. }
  887. return new BABYLON.Vector3(pitch, yaw, roll);
  888. };
  889. return Vector3;
  890. })();
  891. BABYLON.Vector3 = Vector3;
  892. //Vector4 class created for EulerAngle class conversion to Quaternion
  893. var Vector4 = (function () {
  894. function Vector4(x, y, z, w) {
  895. this.x = x;
  896. this.y = y;
  897. this.z = z;
  898. this.w = w;
  899. }
  900. Vector4.prototype.toString = function () {
  901. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  902. };
  903. // Operators
  904. Vector4.prototype.asArray = function () {
  905. var result = [];
  906. this.toArray(result, 0);
  907. return result;
  908. };
  909. Vector4.prototype.toArray = function (array, index) {
  910. if (index === undefined) {
  911. index = 0;
  912. }
  913. array[index] = this.x;
  914. array[index + 1] = this.y;
  915. array[index + 2] = this.z;
  916. array[index + 3] = this.w;
  917. return this;
  918. };
  919. Vector4.prototype.addInPlace = function (otherVector) {
  920. this.x += otherVector.x;
  921. this.y += otherVector.y;
  922. this.z += otherVector.z;
  923. this.w += otherVector.w;
  924. return this;
  925. };
  926. Vector4.prototype.add = function (otherVector) {
  927. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  928. };
  929. Vector4.prototype.addToRef = function (otherVector, result) {
  930. result.x = this.x + otherVector.x;
  931. result.y = this.y + otherVector.y;
  932. result.z = this.z + otherVector.z;
  933. result.w = this.w + otherVector.w;
  934. return this;
  935. };
  936. Vector4.prototype.subtractInPlace = function (otherVector) {
  937. this.x -= otherVector.x;
  938. this.y -= otherVector.y;
  939. this.z -= otherVector.z;
  940. this.w -= otherVector.w;
  941. return this;
  942. };
  943. Vector4.prototype.subtract = function (otherVector) {
  944. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  945. };
  946. Vector4.prototype.subtractToRef = function (otherVector, result) {
  947. result.x = this.x - otherVector.x;
  948. result.y = this.y - otherVector.y;
  949. result.z = this.z - otherVector.z;
  950. result.w = this.w - otherVector.w;
  951. return this;
  952. };
  953. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  954. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  955. };
  956. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  957. result.x = this.x - x;
  958. result.y = this.y - y;
  959. result.z = this.z - z;
  960. result.w = this.w - w;
  961. return this;
  962. };
  963. Vector4.prototype.negate = function () {
  964. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  965. };
  966. Vector4.prototype.scaleInPlace = function (scale) {
  967. this.x *= scale;
  968. this.y *= scale;
  969. this.z *= scale;
  970. this.w *= scale;
  971. return this;
  972. };
  973. Vector4.prototype.scale = function (scale) {
  974. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  975. };
  976. Vector4.prototype.scaleToRef = function (scale, result) {
  977. result.x = this.x * scale;
  978. result.y = this.y * scale;
  979. result.z = this.z * scale;
  980. result.w = this.w * scale;
  981. };
  982. Vector4.prototype.equals = function (otherVector) {
  983. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  984. };
  985. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  986. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon &&
  987. Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon &&
  988. Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon &&
  989. Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  990. };
  991. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  992. return this.x === x && this.y === y && this.z === z && this.w === w;
  993. };
  994. Vector4.prototype.multiplyInPlace = function (otherVector) {
  995. this.x *= otherVector.x;
  996. this.y *= otherVector.y;
  997. this.z *= otherVector.z;
  998. this.w *= otherVector.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.multiply = function (otherVector) {
  1002. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1003. };
  1004. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1005. result.x = this.x * otherVector.x;
  1006. result.y = this.y * otherVector.y;
  1007. result.z = this.z * otherVector.z;
  1008. result.w = this.w * otherVector.w;
  1009. return this;
  1010. };
  1011. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1012. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1013. };
  1014. Vector4.prototype.divide = function (otherVector) {
  1015. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1016. };
  1017. Vector4.prototype.divideToRef = function (otherVector, result) {
  1018. result.x = this.x / otherVector.x;
  1019. result.y = this.y / otherVector.y;
  1020. result.z = this.z / otherVector.z;
  1021. result.w = this.w / otherVector.w;
  1022. return this;
  1023. };
  1024. Vector4.prototype.MinimizeInPlace = function (other) {
  1025. if (other.x < this.x)
  1026. this.x = other.x;
  1027. if (other.y < this.y)
  1028. this.y = other.y;
  1029. if (other.z < this.z)
  1030. this.z = other.z;
  1031. if (other.w < this.w)
  1032. this.w = other.w;
  1033. return this;
  1034. };
  1035. Vector4.prototype.MaximizeInPlace = function (other) {
  1036. if (other.x > this.x)
  1037. this.x = other.x;
  1038. if (other.y > this.y)
  1039. this.y = other.y;
  1040. if (other.z > this.z)
  1041. this.z = other.z;
  1042. if (other.w > this.w)
  1043. this.w = other.w;
  1044. return this;
  1045. };
  1046. // Properties
  1047. Vector4.prototype.length = function () {
  1048. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1049. };
  1050. Vector4.prototype.lengthSquared = function () {
  1051. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1052. };
  1053. // Methods
  1054. Vector4.prototype.normalize = function () {
  1055. var len = this.length();
  1056. if (len === 0)
  1057. return this;
  1058. var num = 1.0 / len;
  1059. this.x *= num;
  1060. this.y *= num;
  1061. this.z *= num;
  1062. this.w *= num;
  1063. return this;
  1064. };
  1065. Vector4.prototype.clone = function () {
  1066. return new Vector4(this.x, this.y, this.z, this.w);
  1067. };
  1068. Vector4.prototype.copyFrom = function (source) {
  1069. this.x = source.x;
  1070. this.y = source.y;
  1071. this.z = source.z;
  1072. this.w = source.w;
  1073. return this;
  1074. };
  1075. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1076. this.x = x;
  1077. this.y = y;
  1078. this.z = z;
  1079. this.w = w;
  1080. return this;
  1081. };
  1082. // Statics
  1083. Vector4.FromArray = function (array, offset) {
  1084. if (!offset) {
  1085. offset = 0;
  1086. }
  1087. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1088. };
  1089. Vector4.FromArrayToRef = function (array, offset, result) {
  1090. result.x = array[offset];
  1091. result.y = array[offset + 1];
  1092. result.z = array[offset + 2];
  1093. result.w = array[offset + 3];
  1094. };
  1095. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1096. result.x = array[offset];
  1097. result.y = array[offset + 1];
  1098. result.z = array[offset + 2];
  1099. result.w = array[offset + 3];
  1100. };
  1101. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1102. result.x = x;
  1103. result.y = y;
  1104. result.z = z;
  1105. result.w = w;
  1106. };
  1107. Vector4.Zero = function () {
  1108. return new Vector4(0, 0, 0, 0);
  1109. };
  1110. Vector4.Normalize = function (vector) {
  1111. var result = Vector4.Zero();
  1112. Vector4.NormalizeToRef(vector, result);
  1113. return result;
  1114. };
  1115. Vector4.NormalizeToRef = function (vector, result) {
  1116. result.copyFrom(vector);
  1117. result.normalize();
  1118. };
  1119. Vector4.Minimize = function (left, right) {
  1120. var min = left.clone();
  1121. min.MinimizeInPlace(right);
  1122. return min;
  1123. };
  1124. Vector4.Maximize = function (left, right) {
  1125. var max = left.clone();
  1126. max.MaximizeInPlace(right);
  1127. return max;
  1128. };
  1129. Vector4.Distance = function (value1, value2) {
  1130. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1131. };
  1132. Vector4.DistanceSquared = function (value1, value2) {
  1133. var x = value1.x - value2.x;
  1134. var y = value1.y - value2.y;
  1135. var z = value1.z - value2.z;
  1136. var w = value1.w - value2.w;
  1137. return (x * x) + (y * y) + (z * z) + (w * w);
  1138. };
  1139. Vector4.Center = function (value1, value2) {
  1140. var center = value1.add(value2);
  1141. center.scaleInPlace(0.5);
  1142. return center;
  1143. };
  1144. return Vector4;
  1145. })();
  1146. BABYLON.Vector4 = Vector4;
  1147. var Quaternion = (function () {
  1148. function Quaternion(x, y, z, w) {
  1149. if (x === void 0) { x = 0; }
  1150. if (y === void 0) { y = 0; }
  1151. if (z === void 0) { z = 0; }
  1152. if (w === void 0) { w = 1; }
  1153. this.x = x;
  1154. this.y = y;
  1155. this.z = z;
  1156. this.w = w;
  1157. }
  1158. Quaternion.prototype.toString = function () {
  1159. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1160. };
  1161. Quaternion.prototype.asArray = function () {
  1162. return [this.x, this.y, this.z, this.w];
  1163. };
  1164. Quaternion.prototype.equals = function (otherQuaternion) {
  1165. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1166. };
  1167. Quaternion.prototype.clone = function () {
  1168. return new Quaternion(this.x, this.y, this.z, this.w);
  1169. };
  1170. Quaternion.prototype.copyFrom = function (other) {
  1171. this.x = other.x;
  1172. this.y = other.y;
  1173. this.z = other.z;
  1174. this.w = other.w;
  1175. return this;
  1176. };
  1177. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1178. this.x = x;
  1179. this.y = y;
  1180. this.z = z;
  1181. this.w = w;
  1182. return this;
  1183. };
  1184. Quaternion.prototype.add = function (other) {
  1185. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1186. };
  1187. Quaternion.prototype.subtract = function (other) {
  1188. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1189. };
  1190. Quaternion.prototype.scale = function (value) {
  1191. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1192. };
  1193. Quaternion.prototype.multiply = function (q1) {
  1194. var result = new Quaternion(0, 0, 0, 1.0);
  1195. this.multiplyToRef(q1, result);
  1196. return result;
  1197. };
  1198. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1199. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1200. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1201. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1202. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1203. return this;
  1204. };
  1205. Quaternion.prototype.length = function () {
  1206. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1207. };
  1208. Quaternion.prototype.normalize = function () {
  1209. var length = 1.0 / this.length();
  1210. this.x *= length;
  1211. this.y *= length;
  1212. this.z *= length;
  1213. this.w *= length;
  1214. return this;
  1215. };
  1216. Quaternion.prototype.toEulerAngles = function () {
  1217. var result = Vector3.Zero();
  1218. this.toEulerAnglesToRef(result);
  1219. return result;
  1220. };
  1221. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1222. //result is an EulerAngles in the in the z-x-z convention
  1223. var qx = this.x;
  1224. var qy = this.y;
  1225. var qz = this.z;
  1226. var qw = this.w;
  1227. var qxy = qx * qy;
  1228. var qxz = qx * qz;
  1229. var qwy = qw * qy;
  1230. var qwz = qw * qz;
  1231. var qwx = qw * qx;
  1232. var qyz = qy * qz;
  1233. var sqx = qx * qx;
  1234. var sqy = qy * qy;
  1235. var determinant = sqx + sqy;
  1236. if (determinant !== 0.000 && determinant !== 1.000) {
  1237. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1238. result.y = Math.acos(1 - 2 * determinant);
  1239. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1240. }
  1241. else {
  1242. if (determinant === 0.0) {
  1243. result.x = 0.0;
  1244. result.y = 0.0;
  1245. 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)
  1246. }
  1247. else {
  1248. 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)
  1249. result.y = Math.PI;
  1250. result.z = 0.0;
  1251. }
  1252. }
  1253. return this;
  1254. };
  1255. Quaternion.prototype.toRotationMatrix = function (result) {
  1256. var xx = this.x * this.x;
  1257. var yy = this.y * this.y;
  1258. var zz = this.z * this.z;
  1259. var xy = this.x * this.y;
  1260. var zw = this.z * this.w;
  1261. var zx = this.z * this.x;
  1262. var yw = this.y * this.w;
  1263. var yz = this.y * this.z;
  1264. var xw = this.x * this.w;
  1265. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1266. result.m[1] = 2.0 * (xy + zw);
  1267. result.m[2] = 2.0 * (zx - yw);
  1268. result.m[3] = 0;
  1269. result.m[4] = 2.0 * (xy - zw);
  1270. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1271. result.m[6] = 2.0 * (yz + xw);
  1272. result.m[7] = 0;
  1273. result.m[8] = 2.0 * (zx + yw);
  1274. result.m[9] = 2.0 * (yz - xw);
  1275. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1276. result.m[11] = 0;
  1277. result.m[12] = 0;
  1278. result.m[13] = 0;
  1279. result.m[14] = 0;
  1280. result.m[15] = 1.0;
  1281. return this;
  1282. };
  1283. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1284. Quaternion.FromRotationMatrixToRef(matrix, this);
  1285. return this;
  1286. };
  1287. // Statics
  1288. Quaternion.FromRotationMatrix = function (matrix) {
  1289. var result = new Quaternion();
  1290. Quaternion.FromRotationMatrixToRef(matrix, result);
  1291. return result;
  1292. };
  1293. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1294. var data = matrix.m;
  1295. var m11 = data[0], m12 = data[4], m13 = data[8];
  1296. var m21 = data[1], m22 = data[5], m23 = data[9];
  1297. var m31 = data[2], m32 = data[6], m33 = data[10];
  1298. var trace = m11 + m22 + m33;
  1299. var s;
  1300. if (trace > 0) {
  1301. s = 0.5 / Math.sqrt(trace + 1.0);
  1302. result.w = 0.25 / s;
  1303. result.x = (m32 - m23) * s;
  1304. result.y = (m13 - m31) * s;
  1305. result.z = (m21 - m12) * s;
  1306. }
  1307. else if (m11 > m22 && m11 > m33) {
  1308. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1309. result.w = (m32 - m23) / s;
  1310. result.x = 0.25 * s;
  1311. result.y = (m12 + m21) / s;
  1312. result.z = (m13 + m31) / s;
  1313. }
  1314. else if (m22 > m33) {
  1315. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1316. result.w = (m13 - m31) / s;
  1317. result.x = (m12 + m21) / s;
  1318. result.y = 0.25 * s;
  1319. result.z = (m23 + m32) / s;
  1320. }
  1321. else {
  1322. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1323. result.w = (m21 - m12) / s;
  1324. result.x = (m13 + m31) / s;
  1325. result.y = (m23 + m32) / s;
  1326. result.z = 0.25 * s;
  1327. }
  1328. };
  1329. Quaternion.Inverse = function (q) {
  1330. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1331. };
  1332. Quaternion.Identity = function () {
  1333. return new Quaternion(0, 0, 0, 1);
  1334. };
  1335. Quaternion.RotationAxis = function (axis, angle) {
  1336. var result = new Quaternion();
  1337. var sin = Math.sin(angle / 2);
  1338. result.w = Math.cos(angle / 2);
  1339. result.x = axis.x * sin;
  1340. result.y = axis.y * sin;
  1341. result.z = axis.z * sin;
  1342. return result;
  1343. };
  1344. Quaternion.FromArray = function (array, offset) {
  1345. if (!offset) {
  1346. offset = 0;
  1347. }
  1348. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1349. };
  1350. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1351. var result = new Quaternion();
  1352. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1353. return result;
  1354. };
  1355. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1356. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1357. var halfRoll = roll * 0.5;
  1358. var halfPitch = pitch * 0.5;
  1359. var halfYaw = yaw * 0.5;
  1360. var sinRoll = Math.sin(halfRoll);
  1361. var cosRoll = Math.cos(halfRoll);
  1362. var sinPitch = Math.sin(halfPitch);
  1363. var cosPitch = Math.cos(halfPitch);
  1364. var sinYaw = Math.sin(halfYaw);
  1365. var cosYaw = Math.cos(halfYaw);
  1366. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1367. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1368. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1369. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1370. };
  1371. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1372. var result = new Quaternion();
  1373. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1374. return result;
  1375. };
  1376. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1377. // Produces a quaternion from Euler angles in the z-x-z orientation
  1378. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1379. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1380. var halfBeta = beta * 0.5;
  1381. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1382. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1383. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1384. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1385. };
  1386. Quaternion.Slerp = function (left, right, amount) {
  1387. var num2;
  1388. var num3;
  1389. var num = amount;
  1390. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1391. var flag = false;
  1392. if (num4 < 0) {
  1393. flag = true;
  1394. num4 = -num4;
  1395. }
  1396. if (num4 > 0.999999) {
  1397. num3 = 1 - num;
  1398. num2 = flag ? -num : num;
  1399. }
  1400. else {
  1401. var num5 = Math.acos(num4);
  1402. var num6 = (1.0 / Math.sin(num5));
  1403. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1404. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1405. }
  1406. 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));
  1407. };
  1408. return Quaternion;
  1409. })();
  1410. BABYLON.Quaternion = Quaternion;
  1411. var Matrix = (function () {
  1412. function Matrix() {
  1413. this.m = new Float32Array(16);
  1414. }
  1415. // Properties
  1416. Matrix.prototype.isIdentity = function () {
  1417. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1418. return false;
  1419. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1420. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1421. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1422. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1423. return false;
  1424. return true;
  1425. };
  1426. Matrix.prototype.determinant = function () {
  1427. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1428. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1429. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1430. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1431. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1432. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1433. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1434. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1435. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1436. };
  1437. // Methods
  1438. Matrix.prototype.toArray = function () {
  1439. return this.m;
  1440. };
  1441. Matrix.prototype.asArray = function () {
  1442. return this.toArray();
  1443. };
  1444. Matrix.prototype.invert = function () {
  1445. this.invertToRef(this);
  1446. return this;
  1447. };
  1448. Matrix.prototype.invertToRef = function (other) {
  1449. var l1 = this.m[0];
  1450. var l2 = this.m[1];
  1451. var l3 = this.m[2];
  1452. var l4 = this.m[3];
  1453. var l5 = this.m[4];
  1454. var l6 = this.m[5];
  1455. var l7 = this.m[6];
  1456. var l8 = this.m[7];
  1457. var l9 = this.m[8];
  1458. var l10 = this.m[9];
  1459. var l11 = this.m[10];
  1460. var l12 = this.m[11];
  1461. var l13 = this.m[12];
  1462. var l14 = this.m[13];
  1463. var l15 = this.m[14];
  1464. var l16 = this.m[15];
  1465. var l17 = (l11 * l16) - (l12 * l15);
  1466. var l18 = (l10 * l16) - (l12 * l14);
  1467. var l19 = (l10 * l15) - (l11 * l14);
  1468. var l20 = (l9 * l16) - (l12 * l13);
  1469. var l21 = (l9 * l15) - (l11 * l13);
  1470. var l22 = (l9 * l14) - (l10 * l13);
  1471. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1472. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1473. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1474. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1475. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1476. var l28 = (l7 * l16) - (l8 * l15);
  1477. var l29 = (l6 * l16) - (l8 * l14);
  1478. var l30 = (l6 * l15) - (l7 * l14);
  1479. var l31 = (l5 * l16) - (l8 * l13);
  1480. var l32 = (l5 * l15) - (l7 * l13);
  1481. var l33 = (l5 * l14) - (l6 * l13);
  1482. var l34 = (l7 * l12) - (l8 * l11);
  1483. var l35 = (l6 * l12) - (l8 * l10);
  1484. var l36 = (l6 * l11) - (l7 * l10);
  1485. var l37 = (l5 * l12) - (l8 * l9);
  1486. var l38 = (l5 * l11) - (l7 * l9);
  1487. var l39 = (l5 * l10) - (l6 * l9);
  1488. other.m[0] = l23 * l27;
  1489. other.m[4] = l24 * l27;
  1490. other.m[8] = l25 * l27;
  1491. other.m[12] = l26 * l27;
  1492. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1493. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1494. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1495. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1496. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1497. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1498. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1499. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1500. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1501. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1502. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1503. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1504. return this;
  1505. };
  1506. Matrix.prototype.invertToRefSIMD = function (other) {
  1507. var src = this.m;
  1508. var dest = other.m;
  1509. var row0, row1, row2, row3;
  1510. var tmp1;
  1511. var minor0, minor1, minor2, minor3;
  1512. var det;
  1513. // Load the 4 rows
  1514. var src0 = SIMD.float32x4.load(src, 0);
  1515. var src1 = SIMD.float32x4.load(src, 4);
  1516. var src2 = SIMD.float32x4.load(src, 8);
  1517. var src3 = SIMD.float32x4.load(src, 12);
  1518. // Transpose the source matrix. Sort of. Not a true transpose operation
  1519. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1520. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1521. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1522. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1523. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1524. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1525. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1526. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1527. // This is a true transposition, but it will lead to an incorrect result
  1528. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1529. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1530. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1531. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1532. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1533. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1534. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1535. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1536. // ----
  1537. tmp1 = SIMD.float32x4.mul(row2, row3);
  1538. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1539. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1540. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1541. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1542. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1543. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1544. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1545. // ----
  1546. tmp1 = SIMD.float32x4.mul(row1, row2);
  1547. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1548. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1549. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1550. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1551. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1552. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1553. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1554. // ----
  1555. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1556. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1557. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1558. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1559. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1560. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1561. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1562. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1563. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1564. // ----
  1565. tmp1 = SIMD.float32x4.mul(row0, row1);
  1566. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1567. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1568. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1569. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1570. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1571. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1572. // ----
  1573. tmp1 = SIMD.float32x4.mul(row0, row3);
  1574. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1575. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1576. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1577. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1578. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1579. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1580. // ----
  1581. tmp1 = SIMD.float32x4.mul(row0, row2);
  1582. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1583. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1584. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1585. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1586. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1587. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1588. // Compute determinant
  1589. det = SIMD.float32x4.mul(row0, minor0);
  1590. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1591. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1592. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1593. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1594. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1595. // These shuffles aren't necessary if the faulty transposition is done
  1596. // up at the top of this function.
  1597. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1598. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1599. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1600. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1601. // Compute final values by multiplying with 1/det
  1602. minor0 = SIMD.float32x4.mul(det, minor0);
  1603. minor1 = SIMD.float32x4.mul(det, minor1);
  1604. minor2 = SIMD.float32x4.mul(det, minor2);
  1605. minor3 = SIMD.float32x4.mul(det, minor3);
  1606. SIMD.float32x4.store(dest, 0, minor0);
  1607. SIMD.float32x4.store(dest, 4, minor1);
  1608. SIMD.float32x4.store(dest, 8, minor2);
  1609. SIMD.float32x4.store(dest, 12, minor3);
  1610. return this;
  1611. };
  1612. Matrix.prototype.setTranslation = function (vector3) {
  1613. this.m[12] = vector3.x;
  1614. this.m[13] = vector3.y;
  1615. this.m[14] = vector3.z;
  1616. return this;
  1617. };
  1618. Matrix.prototype.multiply = function (other) {
  1619. var result = new Matrix();
  1620. this.multiplyToRef(other, result);
  1621. return result;
  1622. };
  1623. Matrix.prototype.copyFrom = function (other) {
  1624. for (var index = 0; index < 16; index++) {
  1625. this.m[index] = other.m[index];
  1626. }
  1627. return this;
  1628. };
  1629. Matrix.prototype.copyToArray = function (array, offset) {
  1630. if (offset === void 0) { offset = 0; }
  1631. for (var index = 0; index < 16; index++) {
  1632. array[offset + index] = this.m[index];
  1633. }
  1634. return this;
  1635. };
  1636. Matrix.prototype.multiplyToRef = function (other, result) {
  1637. this.multiplyToArray(other, result.m, 0);
  1638. return this;
  1639. };
  1640. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1641. var tm0 = this.m[0];
  1642. var tm1 = this.m[1];
  1643. var tm2 = this.m[2];
  1644. var tm3 = this.m[3];
  1645. var tm4 = this.m[4];
  1646. var tm5 = this.m[5];
  1647. var tm6 = this.m[6];
  1648. var tm7 = this.m[7];
  1649. var tm8 = this.m[8];
  1650. var tm9 = this.m[9];
  1651. var tm10 = this.m[10];
  1652. var tm11 = this.m[11];
  1653. var tm12 = this.m[12];
  1654. var tm13 = this.m[13];
  1655. var tm14 = this.m[14];
  1656. var tm15 = this.m[15];
  1657. var om0 = other.m[0];
  1658. var om1 = other.m[1];
  1659. var om2 = other.m[2];
  1660. var om3 = other.m[3];
  1661. var om4 = other.m[4];
  1662. var om5 = other.m[5];
  1663. var om6 = other.m[6];
  1664. var om7 = other.m[7];
  1665. var om8 = other.m[8];
  1666. var om9 = other.m[9];
  1667. var om10 = other.m[10];
  1668. var om11 = other.m[11];
  1669. var om12 = other.m[12];
  1670. var om13 = other.m[13];
  1671. var om14 = other.m[14];
  1672. var om15 = other.m[15];
  1673. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1674. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1675. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1676. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1677. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1678. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1679. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1680. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1681. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1682. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1683. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1684. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1685. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1686. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1687. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1688. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1689. return this;
  1690. };
  1691. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1692. if (offset === void 0) { offset = 0; }
  1693. var tm = this.m;
  1694. var om = other.m;
  1695. var om0 = SIMD.float32x4.load(om, 0);
  1696. var om1 = SIMD.float32x4.load(om, 4);
  1697. var om2 = SIMD.float32x4.load(om, 8);
  1698. var om3 = SIMD.float32x4.load(om, 12);
  1699. var tm0 = SIMD.float32x4.load(tm, 0);
  1700. 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)))));
  1701. var tm1 = SIMD.float32x4.load(tm, 4);
  1702. 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)))));
  1703. var tm2 = SIMD.float32x4.load(tm, 8);
  1704. 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)))));
  1705. var tm3 = SIMD.float32x4.load(tm, 12);
  1706. 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)))));
  1707. };
  1708. Matrix.prototype.equals = function (value) {
  1709. return value &&
  1710. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1711. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1712. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1713. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1714. };
  1715. Matrix.prototype.clone = function () {
  1716. 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]);
  1717. };
  1718. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1719. translation.x = this.m[12];
  1720. translation.y = this.m[13];
  1721. translation.z = this.m[14];
  1722. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1723. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1724. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1725. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1726. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1727. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1728. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1729. rotation.x = 0;
  1730. rotation.y = 0;
  1731. rotation.z = 0;
  1732. rotation.w = 1;
  1733. return false;
  1734. }
  1735. 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);
  1736. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1737. return true;
  1738. };
  1739. // Statics
  1740. Matrix.FromArray = function (array, offset) {
  1741. var result = new Matrix();
  1742. if (!offset) {
  1743. offset = 0;
  1744. }
  1745. Matrix.FromArrayToRef(array, offset, result);
  1746. return result;
  1747. };
  1748. Matrix.FromArrayToRef = function (array, offset, result) {
  1749. for (var index = 0; index < 16; index++) {
  1750. result.m[index] = array[index + offset];
  1751. }
  1752. };
  1753. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1754. result.m[0] = initialM11;
  1755. result.m[1] = initialM12;
  1756. result.m[2] = initialM13;
  1757. result.m[3] = initialM14;
  1758. result.m[4] = initialM21;
  1759. result.m[5] = initialM22;
  1760. result.m[6] = initialM23;
  1761. result.m[7] = initialM24;
  1762. result.m[8] = initialM31;
  1763. result.m[9] = initialM32;
  1764. result.m[10] = initialM33;
  1765. result.m[11] = initialM34;
  1766. result.m[12] = initialM41;
  1767. result.m[13] = initialM42;
  1768. result.m[14] = initialM43;
  1769. result.m[15] = initialM44;
  1770. };
  1771. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1772. var result = new Matrix();
  1773. result.m[0] = initialM11;
  1774. result.m[1] = initialM12;
  1775. result.m[2] = initialM13;
  1776. result.m[3] = initialM14;
  1777. result.m[4] = initialM21;
  1778. result.m[5] = initialM22;
  1779. result.m[6] = initialM23;
  1780. result.m[7] = initialM24;
  1781. result.m[8] = initialM31;
  1782. result.m[9] = initialM32;
  1783. result.m[10] = initialM33;
  1784. result.m[11] = initialM34;
  1785. result.m[12] = initialM41;
  1786. result.m[13] = initialM42;
  1787. result.m[14] = initialM43;
  1788. result.m[15] = initialM44;
  1789. return result;
  1790. };
  1791. Matrix.Compose = function (scale, rotation, translation) {
  1792. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1793. var rotationMatrix = Matrix.Identity();
  1794. rotation.toRotationMatrix(rotationMatrix);
  1795. result = result.multiply(rotationMatrix);
  1796. result.setTranslation(translation);
  1797. return result;
  1798. };
  1799. Matrix.Identity = function () {
  1800. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1801. };
  1802. Matrix.IdentityToRef = function (result) {
  1803. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1804. };
  1805. Matrix.Zero = function () {
  1806. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1807. };
  1808. Matrix.RotationX = function (angle) {
  1809. var result = new Matrix();
  1810. Matrix.RotationXToRef(angle, result);
  1811. return result;
  1812. };
  1813. Matrix.Invert = function (source) {
  1814. var result = new Matrix();
  1815. source.invertToRef(result);
  1816. return result;
  1817. };
  1818. Matrix.RotationXToRef = function (angle, result) {
  1819. var s = Math.sin(angle);
  1820. var c = Math.cos(angle);
  1821. result.m[0] = 1.0;
  1822. result.m[15] = 1.0;
  1823. result.m[5] = c;
  1824. result.m[10] = c;
  1825. result.m[9] = -s;
  1826. result.m[6] = s;
  1827. result.m[1] = 0;
  1828. result.m[2] = 0;
  1829. result.m[3] = 0;
  1830. result.m[4] = 0;
  1831. result.m[7] = 0;
  1832. result.m[8] = 0;
  1833. result.m[11] = 0;
  1834. result.m[12] = 0;
  1835. result.m[13] = 0;
  1836. result.m[14] = 0;
  1837. };
  1838. Matrix.RotationY = function (angle) {
  1839. var result = new Matrix();
  1840. Matrix.RotationYToRef(angle, result);
  1841. return result;
  1842. };
  1843. Matrix.RotationYToRef = function (angle, result) {
  1844. var s = Math.sin(angle);
  1845. var c = Math.cos(angle);
  1846. result.m[5] = 1.0;
  1847. result.m[15] = 1.0;
  1848. result.m[0] = c;
  1849. result.m[2] = -s;
  1850. result.m[8] = s;
  1851. result.m[10] = c;
  1852. result.m[1] = 0;
  1853. result.m[3] = 0;
  1854. result.m[4] = 0;
  1855. result.m[6] = 0;
  1856. result.m[7] = 0;
  1857. result.m[9] = 0;
  1858. result.m[11] = 0;
  1859. result.m[12] = 0;
  1860. result.m[13] = 0;
  1861. result.m[14] = 0;
  1862. };
  1863. Matrix.RotationZ = function (angle) {
  1864. var result = new Matrix();
  1865. Matrix.RotationZToRef(angle, result);
  1866. return result;
  1867. };
  1868. Matrix.RotationZToRef = function (angle, result) {
  1869. var s = Math.sin(angle);
  1870. var c = Math.cos(angle);
  1871. result.m[10] = 1.0;
  1872. result.m[15] = 1.0;
  1873. result.m[0] = c;
  1874. result.m[1] = s;
  1875. result.m[4] = -s;
  1876. result.m[5] = c;
  1877. result.m[2] = 0;
  1878. result.m[3] = 0;
  1879. result.m[6] = 0;
  1880. result.m[7] = 0;
  1881. result.m[8] = 0;
  1882. result.m[9] = 0;
  1883. result.m[11] = 0;
  1884. result.m[12] = 0;
  1885. result.m[13] = 0;
  1886. result.m[14] = 0;
  1887. };
  1888. Matrix.RotationAxis = function (axis, angle) {
  1889. var s = Math.sin(-angle);
  1890. var c = Math.cos(-angle);
  1891. var c1 = 1 - c;
  1892. axis.normalize();
  1893. var result = Matrix.Zero();
  1894. result.m[0] = (axis.x * axis.x) * c1 + c;
  1895. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1896. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1897. result.m[3] = 0.0;
  1898. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1899. result.m[5] = (axis.y * axis.y) * c1 + c;
  1900. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1901. result.m[7] = 0.0;
  1902. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1903. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1904. result.m[10] = (axis.z * axis.z) * c1 + c;
  1905. result.m[11] = 0.0;
  1906. result.m[15] = 1.0;
  1907. return result;
  1908. };
  1909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1910. var result = new Matrix();
  1911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1912. return result;
  1913. };
  1914. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1915. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1916. this._tempQuaternion.toRotationMatrix(result);
  1917. };
  1918. Matrix.Scaling = function (x, y, z) {
  1919. var result = Matrix.Zero();
  1920. Matrix.ScalingToRef(x, y, z, result);
  1921. return result;
  1922. };
  1923. Matrix.ScalingToRef = function (x, y, z, result) {
  1924. result.m[0] = x;
  1925. result.m[1] = 0;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[4] = 0;
  1929. result.m[5] = y;
  1930. result.m[6] = 0;
  1931. result.m[7] = 0;
  1932. result.m[8] = 0;
  1933. result.m[9] = 0;
  1934. result.m[10] = z;
  1935. result.m[11] = 0;
  1936. result.m[12] = 0;
  1937. result.m[13] = 0;
  1938. result.m[14] = 0;
  1939. result.m[15] = 1.0;
  1940. };
  1941. Matrix.Translation = function (x, y, z) {
  1942. var result = Matrix.Identity();
  1943. Matrix.TranslationToRef(x, y, z, result);
  1944. return result;
  1945. };
  1946. Matrix.TranslationToRef = function (x, y, z, result) {
  1947. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1948. };
  1949. Matrix.LookAtLH = function (eye, target, up) {
  1950. var result = Matrix.Zero();
  1951. Matrix.LookAtLHToRef(eye, target, up, result);
  1952. return result;
  1953. };
  1954. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1955. // Z axis
  1956. target.subtractToRef(eye, this._zAxis);
  1957. this._zAxis.normalize();
  1958. // X axis
  1959. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1960. this._xAxis.normalize();
  1961. // Y axis
  1962. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1963. this._yAxis.normalize();
  1964. // Eye angles
  1965. var ex = -Vector3.Dot(this._xAxis, eye);
  1966. var ey = -Vector3.Dot(this._yAxis, eye);
  1967. var ez = -Vector3.Dot(this._zAxis, eye);
  1968. 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);
  1969. };
  1970. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1971. var out = result.m;
  1972. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1973. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1974. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1975. // cc.kmVec3Subtract(f, pCenter, pEye);
  1976. var f = SIMD.float32x4.sub(center, eye);
  1977. // cc.kmVec3Normalize(f, f);
  1978. var tmp = SIMD.float32x4.mul(f, f);
  1979. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1980. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1981. // cc.kmVec3Assign(up, pUp);
  1982. // cc.kmVec3Normalize(up, up);
  1983. tmp = SIMD.float32x4.mul(up, up);
  1984. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1985. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1986. // cc.kmVec3Cross(s, f, up);
  1987. 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)));
  1988. // cc.kmVec3Normalize(s, s);
  1989. tmp = SIMD.float32x4.mul(s, s);
  1990. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1991. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1992. // cc.kmVec3Cross(u, s, f);
  1993. 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)));
  1994. // cc.kmVec3Normalize(s, s);
  1995. tmp = SIMD.float32x4.mul(s, s);
  1996. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1997. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1998. var zero = SIMD.float32x4.splat(0.0);
  1999. s = SIMD.float32x4.neg(s);
  2000. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2001. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2002. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2003. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2004. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2005. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2006. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2007. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2008. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2009. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2010. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2011. var b3 = SIMD.float32x4.neg(eye);
  2012. b3 = SIMD.float32x4.withW(b3, 1.0);
  2013. 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)))));
  2014. 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)))));
  2015. 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)))));
  2016. 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)))));
  2017. };
  2018. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2019. var matrix = Matrix.Zero();
  2020. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2021. return matrix;
  2022. };
  2023. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2024. var hw = 2.0 / width;
  2025. var hh = 2.0 / height;
  2026. var id = 1.0 / (zfar - znear);
  2027. var nid = znear / (znear - zfar);
  2028. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2029. };
  2030. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2031. var matrix = Matrix.Zero();
  2032. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2033. return matrix;
  2034. };
  2035. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2036. result.m[0] = 2.0 / (right - left);
  2037. result.m[1] = result.m[2] = result.m[3] = 0;
  2038. result.m[5] = 2.0 / (top - bottom);
  2039. result.m[4] = result.m[6] = result.m[7] = 0;
  2040. result.m[10] = -1.0 / (znear - zfar);
  2041. result.m[8] = result.m[9] = result.m[11] = 0;
  2042. result.m[12] = (left + right) / (left - right);
  2043. result.m[13] = (top + bottom) / (bottom - top);
  2044. result.m[14] = znear / (znear - zfar);
  2045. result.m[15] = 1.0;
  2046. };
  2047. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2048. var matrix = Matrix.Zero();
  2049. matrix.m[0] = (2.0 * znear) / width;
  2050. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2051. matrix.m[5] = (2.0 * znear) / height;
  2052. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2053. matrix.m[10] = -zfar / (znear - zfar);
  2054. matrix.m[8] = matrix.m[9] = 0.0;
  2055. matrix.m[11] = 1.0;
  2056. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2057. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2058. return matrix;
  2059. };
  2060. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2061. var matrix = Matrix.Zero();
  2062. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2063. return matrix;
  2064. };
  2065. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2066. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2067. var tan = 1.0 / (Math.tan(fov * 0.5));
  2068. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2069. if (v_fixed) {
  2070. result.m[0] = tan / aspect;
  2071. }
  2072. else {
  2073. result.m[0] = tan;
  2074. }
  2075. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2076. if (v_fixed) {
  2077. result.m[5] = tan;
  2078. }
  2079. else {
  2080. result.m[5] = tan * aspect;
  2081. }
  2082. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2083. result.m[8] = result.m[9] = 0.0;
  2084. result.m[10] = -zfar / (znear - zfar);
  2085. result.m[11] = 1.0;
  2086. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2087. result.m[14] = (znear * zfar) / (znear - zfar);
  2088. };
  2089. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2090. var cw = viewport.width;
  2091. var ch = viewport.height;
  2092. var cx = viewport.x;
  2093. var cy = viewport.y;
  2094. 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);
  2095. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2096. };
  2097. Matrix.Transpose = function (matrix) {
  2098. var result = new Matrix();
  2099. result.m[0] = matrix.m[0];
  2100. result.m[1] = matrix.m[4];
  2101. result.m[2] = matrix.m[8];
  2102. result.m[3] = matrix.m[12];
  2103. result.m[4] = matrix.m[1];
  2104. result.m[5] = matrix.m[5];
  2105. result.m[6] = matrix.m[9];
  2106. result.m[7] = matrix.m[13];
  2107. result.m[8] = matrix.m[2];
  2108. result.m[9] = matrix.m[6];
  2109. result.m[10] = matrix.m[10];
  2110. result.m[11] = matrix.m[14];
  2111. result.m[12] = matrix.m[3];
  2112. result.m[13] = matrix.m[7];
  2113. result.m[14] = matrix.m[11];
  2114. result.m[15] = matrix.m[15];
  2115. return result;
  2116. };
  2117. Matrix.Reflection = function (plane) {
  2118. var matrix = new Matrix();
  2119. Matrix.ReflectionToRef(plane, matrix);
  2120. return matrix;
  2121. };
  2122. Matrix.ReflectionToRef = function (plane, result) {
  2123. plane.normalize();
  2124. var x = plane.normal.x;
  2125. var y = plane.normal.y;
  2126. var z = plane.normal.z;
  2127. var temp = -2 * x;
  2128. var temp2 = -2 * y;
  2129. var temp3 = -2 * z;
  2130. result.m[0] = (temp * x) + 1;
  2131. result.m[1] = temp2 * x;
  2132. result.m[2] = temp3 * x;
  2133. result.m[3] = 0.0;
  2134. result.m[4] = temp * y;
  2135. result.m[5] = (temp2 * y) + 1;
  2136. result.m[6] = temp3 * y;
  2137. result.m[7] = 0.0;
  2138. result.m[8] = temp * z;
  2139. result.m[9] = temp2 * z;
  2140. result.m[10] = (temp3 * z) + 1;
  2141. result.m[11] = 0.0;
  2142. result.m[12] = temp * plane.d;
  2143. result.m[13] = temp2 * plane.d;
  2144. result.m[14] = temp3 * plane.d;
  2145. result.m[15] = 1.0;
  2146. };
  2147. Matrix._tempQuaternion = new Quaternion();
  2148. Matrix._xAxis = Vector3.Zero();
  2149. Matrix._yAxis = Vector3.Zero();
  2150. Matrix._zAxis = Vector3.Zero();
  2151. return Matrix;
  2152. })();
  2153. BABYLON.Matrix = Matrix;
  2154. var Plane = (function () {
  2155. function Plane(a, b, c, d) {
  2156. this.normal = new Vector3(a, b, c);
  2157. this.d = d;
  2158. }
  2159. Plane.prototype.asArray = function () {
  2160. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2161. };
  2162. // Methods
  2163. Plane.prototype.clone = function () {
  2164. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2165. };
  2166. Plane.prototype.normalize = function () {
  2167. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2168. var magnitude = 0;
  2169. if (norm !== 0) {
  2170. magnitude = 1.0 / norm;
  2171. }
  2172. this.normal.x *= magnitude;
  2173. this.normal.y *= magnitude;
  2174. this.normal.z *= magnitude;
  2175. this.d *= magnitude;
  2176. return this;
  2177. };
  2178. Plane.prototype.transform = function (transformation) {
  2179. var transposedMatrix = Matrix.Transpose(transformation);
  2180. var x = this.normal.x;
  2181. var y = this.normal.y;
  2182. var z = this.normal.z;
  2183. var d = this.d;
  2184. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2185. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2186. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2187. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2188. return new Plane(normalX, normalY, normalZ, finalD);
  2189. };
  2190. Plane.prototype.dotCoordinate = function (point) {
  2191. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2192. };
  2193. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2194. var x1 = point2.x - point1.x;
  2195. var y1 = point2.y - point1.y;
  2196. var z1 = point2.z - point1.z;
  2197. var x2 = point3.x - point1.x;
  2198. var y2 = point3.y - point1.y;
  2199. var z2 = point3.z - point1.z;
  2200. var yz = (y1 * z2) - (z1 * y2);
  2201. var xz = (z1 * x2) - (x1 * z2);
  2202. var xy = (x1 * y2) - (y1 * x2);
  2203. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2204. var invPyth;
  2205. if (pyth !== 0) {
  2206. invPyth = 1.0 / pyth;
  2207. }
  2208. else {
  2209. invPyth = 0;
  2210. }
  2211. this.normal.x = yz * invPyth;
  2212. this.normal.y = xz * invPyth;
  2213. this.normal.z = xy * invPyth;
  2214. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2215. return this;
  2216. };
  2217. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2218. var dot = Vector3.Dot(this.normal, direction);
  2219. return (dot <= epsilon);
  2220. };
  2221. Plane.prototype.signedDistanceTo = function (point) {
  2222. return Vector3.Dot(point, this.normal) + this.d;
  2223. };
  2224. // Statics
  2225. Plane.FromArray = function (array) {
  2226. return new Plane(array[0], array[1], array[2], array[3]);
  2227. };
  2228. Plane.FromPoints = function (point1, point2, point3) {
  2229. var result = new Plane(0, 0, 0, 0);
  2230. result.copyFromPoints(point1, point2, point3);
  2231. return result;
  2232. };
  2233. Plane.FromPositionAndNormal = function (origin, normal) {
  2234. var result = new Plane(0, 0, 0, 0);
  2235. normal.normalize();
  2236. result.normal = normal;
  2237. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2238. return result;
  2239. };
  2240. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2241. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2242. return Vector3.Dot(point, normal) + d;
  2243. };
  2244. return Plane;
  2245. })();
  2246. BABYLON.Plane = Plane;
  2247. var Viewport = (function () {
  2248. function Viewport(x, y, width, height) {
  2249. this.x = x;
  2250. this.y = y;
  2251. this.width = width;
  2252. this.height = height;
  2253. }
  2254. Viewport.prototype.toGlobal = function (engine) {
  2255. var width = engine.getRenderWidth();
  2256. var height = engine.getRenderHeight();
  2257. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2258. };
  2259. return Viewport;
  2260. })();
  2261. BABYLON.Viewport = Viewport;
  2262. var Frustum = (function () {
  2263. function Frustum() {
  2264. }
  2265. Frustum.GetPlanes = function (transform) {
  2266. var frustumPlanes = [];
  2267. for (var index = 0; index < 6; index++) {
  2268. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2269. }
  2270. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2271. return frustumPlanes;
  2272. };
  2273. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2274. // Near
  2275. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2276. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2277. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2278. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2279. frustumPlanes[0].normalize();
  2280. // Far
  2281. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2282. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2283. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2284. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2285. frustumPlanes[1].normalize();
  2286. // Left
  2287. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2288. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2289. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2290. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2291. frustumPlanes[2].normalize();
  2292. // Right
  2293. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2294. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2295. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2296. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2297. frustumPlanes[3].normalize();
  2298. // Top
  2299. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2300. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2301. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2302. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2303. frustumPlanes[4].normalize();
  2304. // Bottom
  2305. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2306. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2307. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2308. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2309. frustumPlanes[5].normalize();
  2310. };
  2311. return Frustum;
  2312. })();
  2313. BABYLON.Frustum = Frustum;
  2314. var Ray = (function () {
  2315. function Ray(origin, direction, length) {
  2316. if (length === void 0) { length = Number.MAX_VALUE; }
  2317. this.origin = origin;
  2318. this.direction = direction;
  2319. this.length = length;
  2320. }
  2321. // Methods
  2322. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2323. var d = 0.0;
  2324. var maxValue = Number.MAX_VALUE;
  2325. if (Math.abs(this.direction.x) < 0.0000001) {
  2326. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2327. return false;
  2328. }
  2329. }
  2330. else {
  2331. var inv = 1.0 / this.direction.x;
  2332. var min = (minimum.x - this.origin.x) * inv;
  2333. var max = (maximum.x - this.origin.x) * inv;
  2334. if (max === -Infinity) {
  2335. max = Infinity;
  2336. }
  2337. if (min > max) {
  2338. var temp = min;
  2339. min = max;
  2340. max = temp;
  2341. }
  2342. d = Math.max(min, d);
  2343. maxValue = Math.min(max, maxValue);
  2344. if (d > maxValue) {
  2345. return false;
  2346. }
  2347. }
  2348. if (Math.abs(this.direction.y) < 0.0000001) {
  2349. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2350. return false;
  2351. }
  2352. }
  2353. else {
  2354. inv = 1.0 / this.direction.y;
  2355. min = (minimum.y - this.origin.y) * inv;
  2356. max = (maximum.y - this.origin.y) * inv;
  2357. if (max === -Infinity) {
  2358. max = Infinity;
  2359. }
  2360. if (min > max) {
  2361. temp = min;
  2362. min = max;
  2363. max = temp;
  2364. }
  2365. d = Math.max(min, d);
  2366. maxValue = Math.min(max, maxValue);
  2367. if (d > maxValue) {
  2368. return false;
  2369. }
  2370. }
  2371. if (Math.abs(this.direction.z) < 0.0000001) {
  2372. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2373. return false;
  2374. }
  2375. }
  2376. else {
  2377. inv = 1.0 / this.direction.z;
  2378. min = (minimum.z - this.origin.z) * inv;
  2379. max = (maximum.z - this.origin.z) * inv;
  2380. if (max === -Infinity) {
  2381. max = Infinity;
  2382. }
  2383. if (min > max) {
  2384. temp = min;
  2385. min = max;
  2386. max = temp;
  2387. }
  2388. d = Math.max(min, d);
  2389. maxValue = Math.min(max, maxValue);
  2390. if (d > maxValue) {
  2391. return false;
  2392. }
  2393. }
  2394. return true;
  2395. };
  2396. Ray.prototype.intersectsBox = function (box) {
  2397. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2398. };
  2399. Ray.prototype.intersectsSphere = function (sphere) {
  2400. var x = sphere.center.x - this.origin.x;
  2401. var y = sphere.center.y - this.origin.y;
  2402. var z = sphere.center.z - this.origin.z;
  2403. var pyth = (x * x) + (y * y) + (z * z);
  2404. var rr = sphere.radius * sphere.radius;
  2405. if (pyth <= rr) {
  2406. return true;
  2407. }
  2408. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2409. if (dot < 0.0) {
  2410. return false;
  2411. }
  2412. var temp = pyth - (dot * dot);
  2413. return temp <= rr;
  2414. };
  2415. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2416. if (!this._edge1) {
  2417. this._edge1 = Vector3.Zero();
  2418. this._edge2 = Vector3.Zero();
  2419. this._pvec = Vector3.Zero();
  2420. this._tvec = Vector3.Zero();
  2421. this._qvec = Vector3.Zero();
  2422. }
  2423. vertex1.subtractToRef(vertex0, this._edge1);
  2424. vertex2.subtractToRef(vertex0, this._edge2);
  2425. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2426. var det = Vector3.Dot(this._edge1, this._pvec);
  2427. if (det === 0) {
  2428. return null;
  2429. }
  2430. var invdet = 1 / det;
  2431. this.origin.subtractToRef(vertex0, this._tvec);
  2432. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2433. if (bu < 0 || bu > 1.0) {
  2434. return null;
  2435. }
  2436. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2437. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2438. if (bv < 0 || bu + bv > 1.0) {
  2439. return null;
  2440. }
  2441. //check if the distance is longer than the predefined length.
  2442. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2443. if (distance > this.length) {
  2444. return null;
  2445. }
  2446. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2447. };
  2448. // Statics
  2449. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2450. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2451. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2452. var direction = end.subtract(start);
  2453. direction.normalize();
  2454. return new Ray(start, direction);
  2455. };
  2456. /**
  2457. * 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
  2458. * transformed to the given world matrix.
  2459. * @param origin The origin point
  2460. * @param end The end point
  2461. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2462. */
  2463. Ray.CreateNewFromTo = function (origin, end, world) {
  2464. if (world === void 0) { world = Matrix.Identity(); }
  2465. var direction = end.subtract(origin);
  2466. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2467. direction.normalize();
  2468. return Ray.Transform(new Ray(origin, direction, length), world);
  2469. };
  2470. Ray.Transform = function (ray, matrix) {
  2471. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2472. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2473. return new Ray(newOrigin, newDirection, ray.length);
  2474. };
  2475. return Ray;
  2476. })();
  2477. BABYLON.Ray = Ray;
  2478. (function (Space) {
  2479. Space[Space["LOCAL"] = 0] = "LOCAL";
  2480. Space[Space["WORLD"] = 1] = "WORLD";
  2481. })(BABYLON.Space || (BABYLON.Space = {}));
  2482. var Space = BABYLON.Space;
  2483. var Axis = (function () {
  2484. function Axis() {
  2485. }
  2486. Axis.X = new Vector3(1, 0, 0);
  2487. Axis.Y = new Vector3(0, 1, 0);
  2488. Axis.Z = new Vector3(0, 0, 1);
  2489. return Axis;
  2490. })();
  2491. BABYLON.Axis = Axis;
  2492. ;
  2493. var BezierCurve = (function () {
  2494. function BezierCurve() {
  2495. }
  2496. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2497. // Extract X (which is equal to time here)
  2498. var f0 = 1 - 3 * x2 + 3 * x1;
  2499. var f1 = 3 * x2 - 6 * x1;
  2500. var f2 = 3 * x1;
  2501. var refinedT = t;
  2502. for (var i = 0; i < 5; i++) {
  2503. var refinedT2 = refinedT * refinedT;
  2504. var refinedT3 = refinedT2 * refinedT;
  2505. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2506. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2507. refinedT -= (x - t) * slope;
  2508. refinedT = Math.min(1, Math.max(0, refinedT));
  2509. }
  2510. // Resolve cubic bezier for the given x
  2511. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2512. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2513. Math.pow(refinedT, 3);
  2514. };
  2515. return BezierCurve;
  2516. })();
  2517. BABYLON.BezierCurve = BezierCurve;
  2518. (function (Orientation) {
  2519. Orientation[Orientation["CW"] = 0] = "CW";
  2520. Orientation[Orientation["CCW"] = 1] = "CCW";
  2521. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2522. var Orientation = BABYLON.Orientation;
  2523. var Angle = (function () {
  2524. function Angle(radians) {
  2525. var _this = this;
  2526. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2527. this.radians = function () { return _this._radians; };
  2528. this._radians = radians;
  2529. if (this._radians < 0)
  2530. this._radians += (2 * Math.PI);
  2531. }
  2532. Angle.BetweenTwoPoints = function (a, b) {
  2533. var delta = b.subtract(a);
  2534. var theta = Math.atan2(delta.y, delta.x);
  2535. return new Angle(theta);
  2536. };
  2537. Angle.FromRadians = function (radians) {
  2538. return new Angle(radians);
  2539. };
  2540. Angle.FromDegrees = function (degrees) {
  2541. return new Angle(degrees * Math.PI / 180);
  2542. };
  2543. return Angle;
  2544. })();
  2545. BABYLON.Angle = Angle;
  2546. var Arc2 = (function () {
  2547. function Arc2(startPoint, midPoint, endPoint) {
  2548. this.startPoint = startPoint;
  2549. this.midPoint = midPoint;
  2550. this.endPoint = endPoint;
  2551. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2552. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2553. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2554. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2555. 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);
  2556. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2557. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2558. var a1 = this.startAngle.degrees();
  2559. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2560. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2561. // angles correction
  2562. if (a2 - a1 > +180.0)
  2563. a2 -= 360.0;
  2564. if (a2 - a1 < -180.0)
  2565. a2 += 360.0;
  2566. if (a3 - a2 > +180.0)
  2567. a3 -= 360.0;
  2568. if (a3 - a2 < -180.0)
  2569. a3 += 360.0;
  2570. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2571. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2572. }
  2573. return Arc2;
  2574. })();
  2575. BABYLON.Arc2 = Arc2;
  2576. var PathCursor = (function () {
  2577. function PathCursor(path) {
  2578. this.path = path;
  2579. this._onchange = new Array();
  2580. this.value = 0;
  2581. this.animations = new Array();
  2582. }
  2583. PathCursor.prototype.getPoint = function () {
  2584. var point = this.path.getPointAtLengthPosition(this.value);
  2585. return new Vector3(point.x, 0, point.y);
  2586. };
  2587. PathCursor.prototype.moveAhead = function (step) {
  2588. if (step === void 0) { step = 0.002; }
  2589. this.move(step);
  2590. return this;
  2591. };
  2592. PathCursor.prototype.moveBack = function (step) {
  2593. if (step === void 0) { step = 0.002; }
  2594. this.move(-step);
  2595. return this;
  2596. };
  2597. PathCursor.prototype.move = function (step) {
  2598. if (Math.abs(step) > 1) {
  2599. throw "step size should be less than 1.";
  2600. }
  2601. this.value += step;
  2602. this.ensureLimits();
  2603. this.raiseOnChange();
  2604. return this;
  2605. };
  2606. PathCursor.prototype.ensureLimits = function () {
  2607. while (this.value > 1) {
  2608. this.value -= 1;
  2609. }
  2610. while (this.value < 0) {
  2611. this.value += 1;
  2612. }
  2613. return this;
  2614. };
  2615. // used by animation engine
  2616. PathCursor.prototype.markAsDirty = function (propertyName) {
  2617. this.ensureLimits();
  2618. this.raiseOnChange();
  2619. return this;
  2620. };
  2621. PathCursor.prototype.raiseOnChange = function () {
  2622. var _this = this;
  2623. this._onchange.forEach(function (f) { return f(_this); });
  2624. return this;
  2625. };
  2626. PathCursor.prototype.onchange = function (f) {
  2627. this._onchange.push(f);
  2628. return this;
  2629. };
  2630. return PathCursor;
  2631. })();
  2632. BABYLON.PathCursor = PathCursor;
  2633. var Path2 = (function () {
  2634. function Path2(x, y) {
  2635. this._points = new Array();
  2636. this._length = 0;
  2637. this.closed = false;
  2638. this._points.push(new Vector2(x, y));
  2639. }
  2640. Path2.prototype.addLineTo = function (x, y) {
  2641. if (closed) {
  2642. BABYLON.Tools.Error("cannot add lines to closed paths");
  2643. return this;
  2644. }
  2645. var newPoint = new Vector2(x, y);
  2646. var previousPoint = this._points[this._points.length - 1];
  2647. this._points.push(newPoint);
  2648. this._length += newPoint.subtract(previousPoint).length();
  2649. return this;
  2650. };
  2651. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2652. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2653. if (closed) {
  2654. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2655. return this;
  2656. }
  2657. var startPoint = this._points[this._points.length - 1];
  2658. var midPoint = new Vector2(midX, midY);
  2659. var endPoint = new Vector2(endX, endY);
  2660. var arc = new Arc2(startPoint, midPoint, endPoint);
  2661. var increment = arc.angle.radians() / numberOfSegments;
  2662. if (arc.orientation === Orientation.CW)
  2663. increment *= -1;
  2664. var currentAngle = arc.startAngle.radians() + increment;
  2665. for (var i = 0; i < numberOfSegments; i++) {
  2666. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2667. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2668. this.addLineTo(x, y);
  2669. currentAngle += increment;
  2670. }
  2671. return this;
  2672. };
  2673. Path2.prototype.close = function () {
  2674. this.closed = true;
  2675. return this;
  2676. };
  2677. Path2.prototype.length = function () {
  2678. var result = this._length;
  2679. if (!this.closed) {
  2680. var lastPoint = this._points[this._points.length - 1];
  2681. var firstPoint = this._points[0];
  2682. result += (firstPoint.subtract(lastPoint).length());
  2683. }
  2684. return result;
  2685. };
  2686. Path2.prototype.getPoints = function () {
  2687. return this._points;
  2688. };
  2689. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2690. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2691. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2692. return Vector2.Zero();
  2693. }
  2694. var lengthPosition = normalizedLengthPosition * this.length();
  2695. var previousOffset = 0;
  2696. for (var i = 0; i < this._points.length; i++) {
  2697. var j = (i + 1) % this._points.length;
  2698. var a = this._points[i];
  2699. var b = this._points[j];
  2700. var bToA = b.subtract(a);
  2701. var nextOffset = (bToA.length() + previousOffset);
  2702. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2703. var dir = bToA.normalize();
  2704. var localOffset = lengthPosition - previousOffset;
  2705. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2706. }
  2707. previousOffset = nextOffset;
  2708. }
  2709. BABYLON.Tools.Error("internal error");
  2710. return Vector2.Zero();
  2711. };
  2712. Path2.StartingAt = function (x, y) {
  2713. return new Path2(x, y);
  2714. };
  2715. return Path2;
  2716. })();
  2717. BABYLON.Path2 = Path2;
  2718. var Path3D = (function () {
  2719. function Path3D(path, firstNormal) {
  2720. this.path = path;
  2721. this._curve = new Array();
  2722. this._distances = new Array();
  2723. this._tangents = new Array();
  2724. this._normals = new Array();
  2725. this._binormals = new Array();
  2726. for (var p = 0; p < path.length; p++) {
  2727. this._curve[p] = path[p].clone(); // hard copy
  2728. }
  2729. this._compute(firstNormal);
  2730. }
  2731. Path3D.prototype.getCurve = function () {
  2732. return this._curve;
  2733. };
  2734. Path3D.prototype.getTangents = function () {
  2735. return this._tangents;
  2736. };
  2737. Path3D.prototype.getNormals = function () {
  2738. return this._normals;
  2739. };
  2740. Path3D.prototype.getBinormals = function () {
  2741. return this._binormals;
  2742. };
  2743. Path3D.prototype.getDistances = function () {
  2744. return this._distances;
  2745. };
  2746. Path3D.prototype.update = function (path, firstNormal) {
  2747. for (var p = 0; p < path.length; p++) {
  2748. this._curve[p].x = path[p].x;
  2749. this._curve[p].y = path[p].y;
  2750. this._curve[p].z = path[p].z;
  2751. }
  2752. this._compute(firstNormal);
  2753. return this;
  2754. };
  2755. // private function compute() : computes tangents, normals and binormals
  2756. Path3D.prototype._compute = function (firstNormal) {
  2757. var l = this._curve.length;
  2758. // first and last tangents
  2759. this._tangents[0] = this._getFirstNonNullVector(0);
  2760. this._tangents[0].normalize();
  2761. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2762. this._tangents[l - 1].normalize();
  2763. // normals and binormals at first point : arbitrary vector with _normalVector()
  2764. var tg0 = this._tangents[0];
  2765. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2766. this._normals[0] = pp0;
  2767. this._normals[0].normalize();
  2768. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2769. this._binormals[0].normalize();
  2770. this._distances[0] = 0;
  2771. // normals and binormals : next points
  2772. var prev; // previous vector (segment)
  2773. var cur; // current vector (segment)
  2774. var curTang; // current tangent
  2775. var prevNorm; // previous normal
  2776. var prevBinor; // previous binormal
  2777. for (var i = 1; i < l; i++) {
  2778. // tangents
  2779. prev = this._getLastNonNullVector(i);
  2780. if (i < l - 1) {
  2781. cur = this._getFirstNonNullVector(i);
  2782. this._tangents[i] = prev.add(cur);
  2783. this._tangents[i].normalize();
  2784. }
  2785. this._distances[i] = this._distances[i - 1] + prev.length();
  2786. // normals and binormals
  2787. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2788. curTang = this._tangents[i];
  2789. prevNorm = this._normals[i - 1];
  2790. prevBinor = this._binormals[i - 1];
  2791. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2792. this._normals[i].normalize();
  2793. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2794. this._binormals[i].normalize();
  2795. }
  2796. };
  2797. // private function getFirstNonNullVector(index)
  2798. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2799. Path3D.prototype._getFirstNonNullVector = function (index) {
  2800. var i = 1;
  2801. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2802. while (nNVector.length() == 0 && index + i + 1 < this._curve.length) {
  2803. i++;
  2804. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2805. }
  2806. return nNVector;
  2807. };
  2808. // private function getLastNonNullVector(index)
  2809. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2810. Path3D.prototype._getLastNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2813. while (nLVector.length() == 0 && index > i + 1) {
  2814. i++;
  2815. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2816. }
  2817. return nLVector;
  2818. };
  2819. // private function normalVector(v0, vt, va) :
  2820. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2821. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2822. Path3D.prototype._normalVector = function (v0, vt, va) {
  2823. var normal0;
  2824. if (va === undefined || va === null) {
  2825. var point;
  2826. if (vt.y !== 1) {
  2827. point = new Vector3(0, -1, 0);
  2828. }
  2829. else if (vt.x !== 1) {
  2830. point = new Vector3(1, 0, 0);
  2831. }
  2832. else if (vt.z !== 1) {
  2833. point = new Vector3(0, 0, 1);
  2834. }
  2835. normal0 = Vector3.Cross(vt, point);
  2836. }
  2837. else {
  2838. normal0 = Vector3.Cross(vt, va);
  2839. Vector3.CrossToRef(normal0, vt, normal0);
  2840. }
  2841. normal0.normalize();
  2842. return normal0;
  2843. };
  2844. return Path3D;
  2845. })();
  2846. BABYLON.Path3D = Path3D;
  2847. var Curve3 = (function () {
  2848. function Curve3(points) {
  2849. this._length = 0;
  2850. this._points = points;
  2851. this._length = this._computeLength(points);
  2852. }
  2853. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2854. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2855. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2856. var bez = new Array();
  2857. var equation = function (t, val0, val1, val2) {
  2858. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2859. return res;
  2860. };
  2861. for (var i = 0; i <= nbPoints; i++) {
  2862. 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)));
  2863. }
  2864. return new Curve3(bez);
  2865. };
  2866. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2867. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2868. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2869. var bez = new Array();
  2870. var equation = function (t, val0, val1, val2, val3) {
  2871. 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;
  2872. return res;
  2873. };
  2874. for (var i = 0; i <= nbPoints; i++) {
  2875. 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)));
  2876. }
  2877. return new Curve3(bez);
  2878. };
  2879. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2880. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2881. var hermite = new Array();
  2882. var step = 1 / nbPoints;
  2883. for (var i = 0; i <= nbPoints; i++) {
  2884. hermite.push(BABYLON.Vector3.Hermite(p1, t1, p2, t2, i * step));
  2885. }
  2886. return new Curve3(hermite);
  2887. };
  2888. Curve3.prototype.getPoints = function () {
  2889. return this._points;
  2890. };
  2891. Curve3.prototype.length = function () {
  2892. return this._length;
  2893. };
  2894. Curve3.prototype.continue = function (curve) {
  2895. var lastPoint = this._points[this._points.length - 1];
  2896. var continuedPoints = this._points.slice();
  2897. var curvePoints = curve.getPoints();
  2898. for (var i = 1; i < curvePoints.length; i++) {
  2899. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2900. }
  2901. var continuedCurve = new Curve3(continuedPoints);
  2902. return continuedCurve;
  2903. };
  2904. Curve3.prototype._computeLength = function (path) {
  2905. var l = 0;
  2906. for (var i = 1; i < path.length; i++) {
  2907. l += (path[i].subtract(path[i - 1])).length();
  2908. }
  2909. return l;
  2910. };
  2911. return Curve3;
  2912. })();
  2913. BABYLON.Curve3 = Curve3;
  2914. // Vertex formats
  2915. var PositionNormalVertex = (function () {
  2916. function PositionNormalVertex(position, normal) {
  2917. if (position === void 0) { position = Vector3.Zero(); }
  2918. if (normal === void 0) { normal = Vector3.Up(); }
  2919. this.position = position;
  2920. this.normal = normal;
  2921. }
  2922. PositionNormalVertex.prototype.clone = function () {
  2923. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2924. };
  2925. return PositionNormalVertex;
  2926. })();
  2927. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2928. var PositionNormalTextureVertex = (function () {
  2929. function PositionNormalTextureVertex(position, normal, uv) {
  2930. if (position === void 0) { position = Vector3.Zero(); }
  2931. if (normal === void 0) { normal = Vector3.Up(); }
  2932. if (uv === void 0) { uv = Vector2.Zero(); }
  2933. this.position = position;
  2934. this.normal = normal;
  2935. this.uv = uv;
  2936. }
  2937. PositionNormalTextureVertex.prototype.clone = function () {
  2938. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2939. };
  2940. return PositionNormalTextureVertex;
  2941. })();
  2942. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2943. // SIMD
  2944. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2945. var previousInvertToRef = Matrix.prototype.invertToRef;
  2946. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2947. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2948. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2949. var SIMDHelper = (function () {
  2950. function SIMDHelper() {
  2951. }
  2952. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2953. get: function () {
  2954. return SIMDHelper._isEnabled;
  2955. },
  2956. enumerable: true,
  2957. configurable: true
  2958. });
  2959. SIMDHelper.DisableSIMD = function () {
  2960. // Replace functions
  2961. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2962. Matrix.prototype.invertToRef = previousInvertToRef;
  2963. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2964. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2965. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2966. SIMDHelper._isEnabled = false;
  2967. };
  2968. SIMDHelper.EnableSIMD = function () {
  2969. if (window.SIMD === undefined) {
  2970. return;
  2971. }
  2972. // Replace functions
  2973. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2974. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2975. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2976. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2977. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2978. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2979. get: function () { return this._data[0]; },
  2980. set: function (value) {
  2981. if (!this._data) {
  2982. this._data = new Float32Array(3);
  2983. }
  2984. this._data[0] = value;
  2985. }
  2986. });
  2987. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2988. get: function () { return this._data[1]; },
  2989. set: function (value) {
  2990. this._data[1] = value;
  2991. }
  2992. });
  2993. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2994. get: function () { return this._data[2]; },
  2995. set: function (value) {
  2996. this._data[2] = value;
  2997. }
  2998. });
  2999. SIMDHelper._isEnabled = true;
  3000. };
  3001. SIMDHelper._isEnabled = false;
  3002. return SIMDHelper;
  3003. })();
  3004. BABYLON.SIMDHelper = SIMDHelper;
  3005. if (window.SIMD !== undefined && window.SIMD.float32x4 && window.SIMD.float32x4.swizzle) {
  3006. SIMDHelper.EnableSIMD();
  3007. }
  3008. })(BABYLON || (BABYLON = {}));
  3009. //# sourceMappingURL=babylon.math.js.map
  3010. var BABYLON;
  3011. (function (BABYLON) {
  3012. var Database = (function () {
  3013. function Database(urlToScene, callbackManifestChecked) {
  3014. // Handling various flavors of prefixed version of IndexedDB
  3015. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3016. this.callbackManifestChecked = callbackManifestChecked;
  3017. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  3018. this.db = null;
  3019. this.enableSceneOffline = false;
  3020. this.enableTexturesOffline = false;
  3021. this.manifestVersionFound = 0;
  3022. this.mustUpdateRessources = false;
  3023. this.hasReachedQuota = false;
  3024. this.checkManifestFile();
  3025. }
  3026. Database.prototype.checkManifestFile = function () {
  3027. var _this = this;
  3028. function noManifestFile() {
  3029. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  3030. that.enableSceneOffline = false;
  3031. that.enableTexturesOffline = false;
  3032. that.callbackManifestChecked(false);
  3033. }
  3034. var that = this;
  3035. var manifestURL = this.currentSceneUrl + ".manifest";
  3036. var xhr = new XMLHttpRequest();
  3037. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3038. xhr.open("GET", manifestURLTimeStamped, true);
  3039. xhr.addEventListener("load", function () {
  3040. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3041. try {
  3042. var manifestFile = JSON.parse(xhr.response);
  3043. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3044. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3045. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3046. _this.manifestVersionFound = manifestFile.version;
  3047. }
  3048. if (_this.callbackManifestChecked) {
  3049. _this.callbackManifestChecked(true);
  3050. }
  3051. }
  3052. catch (ex) {
  3053. noManifestFile();
  3054. }
  3055. }
  3056. else {
  3057. noManifestFile();
  3058. }
  3059. }, false);
  3060. xhr.addEventListener("error", function (event) {
  3061. noManifestFile();
  3062. }, false);
  3063. try {
  3064. xhr.send();
  3065. }
  3066. catch (ex) {
  3067. BABYLON.Tools.Error("Error on XHR send request.");
  3068. that.callbackManifestChecked(false);
  3069. }
  3070. };
  3071. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3072. var _this = this;
  3073. function handleError() {
  3074. that.isSupported = false;
  3075. if (errorCallback)
  3076. errorCallback();
  3077. }
  3078. var that = this;
  3079. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3080. // Your browser doesn't support IndexedDB
  3081. this.isSupported = false;
  3082. if (errorCallback)
  3083. errorCallback();
  3084. }
  3085. else {
  3086. // If the DB hasn't been opened or created yet
  3087. if (!this.db) {
  3088. this.hasReachedQuota = false;
  3089. this.isSupported = true;
  3090. var request = this.idbFactory.open("babylonjs", 1);
  3091. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3092. request.onerror = function (event) {
  3093. handleError();
  3094. };
  3095. // executes when a version change transaction cannot complete due to other active transactions
  3096. request.onblocked = function (event) {
  3097. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3098. handleError();
  3099. };
  3100. // DB has been opened successfully
  3101. request.onsuccess = function (event) {
  3102. _this.db = request.result;
  3103. successCallback();
  3104. };
  3105. // Initialization of the DB. Creating Scenes & Textures stores
  3106. request.onupgradeneeded = function (event) {
  3107. _this.db = (event.target).result;
  3108. try {
  3109. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3110. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3111. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3112. }
  3113. catch (ex) {
  3114. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3115. handleError();
  3116. }
  3117. };
  3118. }
  3119. else {
  3120. if (successCallback)
  3121. successCallback();
  3122. }
  3123. }
  3124. };
  3125. Database.prototype.loadImageFromDB = function (url, image) {
  3126. var _this = this;
  3127. var completeURL = Database.ReturnFullUrlLocation(url);
  3128. var saveAndLoadImage = function () {
  3129. if (!_this.hasReachedQuota && _this.db !== null) {
  3130. // the texture is not yet in the DB, let's try to save it
  3131. _this._saveImageIntoDBAsync(completeURL, image);
  3132. }
  3133. else {
  3134. image.src = url;
  3135. }
  3136. };
  3137. if (!this.mustUpdateRessources) {
  3138. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3139. }
  3140. else {
  3141. saveAndLoadImage();
  3142. }
  3143. };
  3144. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3145. if (this.isSupported && this.db !== null) {
  3146. var texture;
  3147. var transaction = this.db.transaction(["textures"]);
  3148. transaction.onabort = function (event) {
  3149. image.src = url;
  3150. };
  3151. transaction.oncomplete = function (event) {
  3152. var blobTextureURL;
  3153. if (texture) {
  3154. var URL = window.URL || window.webkitURL;
  3155. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3156. image.onerror = function () {
  3157. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3158. image.src = url;
  3159. };
  3160. image.src = blobTextureURL;
  3161. }
  3162. else {
  3163. notInDBCallback();
  3164. }
  3165. };
  3166. var getRequest = transaction.objectStore("textures").get(url);
  3167. getRequest.onsuccess = function (event) {
  3168. texture = (event.target).result;
  3169. };
  3170. getRequest.onerror = function (event) {
  3171. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3172. image.src = url;
  3173. };
  3174. }
  3175. else {
  3176. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3177. image.src = url;
  3178. }
  3179. };
  3180. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3181. var _this = this;
  3182. if (this.isSupported) {
  3183. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3184. var generateBlobUrl = function () {
  3185. var blobTextureURL;
  3186. if (blob) {
  3187. var URL = window.URL || window.webkitURL;
  3188. try {
  3189. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3190. }
  3191. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3192. catch (ex) {
  3193. blobTextureURL = URL.createObjectURL(blob);
  3194. }
  3195. }
  3196. image.src = blobTextureURL;
  3197. };
  3198. if (Database.isUASupportingBlobStorage) {
  3199. var xhr = new XMLHttpRequest(), blob;
  3200. xhr.open("GET", url, true);
  3201. xhr.responseType = "blob";
  3202. xhr.addEventListener("load", function () {
  3203. if (xhr.status === 200) {
  3204. // Blob as response (XHR2)
  3205. blob = xhr.response;
  3206. var transaction = _this.db.transaction(["textures"], "readwrite");
  3207. // the transaction could abort because of a QuotaExceededError error
  3208. transaction.onabort = function (event) {
  3209. try {
  3210. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3211. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3212. this.hasReachedQuota = true;
  3213. }
  3214. }
  3215. catch (ex) { }
  3216. generateBlobUrl();
  3217. };
  3218. transaction.oncomplete = function (event) {
  3219. generateBlobUrl();
  3220. };
  3221. var newTexture = { textureUrl: url, data: blob };
  3222. try {
  3223. // Put the blob into the dabase
  3224. var addRequest = transaction.objectStore("textures").put(newTexture);
  3225. addRequest.onsuccess = function (event) {
  3226. };
  3227. addRequest.onerror = function (event) {
  3228. generateBlobUrl();
  3229. };
  3230. }
  3231. catch (ex) {
  3232. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3233. if (ex.code === 25) {
  3234. Database.isUASupportingBlobStorage = false;
  3235. }
  3236. image.src = url;
  3237. }
  3238. }
  3239. else {
  3240. image.src = url;
  3241. }
  3242. }, false);
  3243. xhr.addEventListener("error", function (event) {
  3244. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3245. image.src = url;
  3246. }, false);
  3247. xhr.send();
  3248. }
  3249. else {
  3250. image.src = url;
  3251. }
  3252. }
  3253. else {
  3254. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3255. image.src = url;
  3256. }
  3257. };
  3258. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3259. var _this = this;
  3260. var updateVersion = function (event) {
  3261. // the version is not yet in the DB or we need to update it
  3262. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3263. };
  3264. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3265. };
  3266. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3267. var _this = this;
  3268. if (this.isSupported) {
  3269. var version;
  3270. try {
  3271. var transaction = this.db.transaction(["versions"]);
  3272. transaction.oncomplete = function (event) {
  3273. if (version) {
  3274. // If the version in the JSON file is > than the version in DB
  3275. if (_this.manifestVersionFound > version.data) {
  3276. _this.mustUpdateRessources = true;
  3277. updateInDBCallback();
  3278. }
  3279. else {
  3280. callback(version.data);
  3281. }
  3282. }
  3283. else {
  3284. _this.mustUpdateRessources = true;
  3285. updateInDBCallback();
  3286. }
  3287. };
  3288. transaction.onabort = function (event) {
  3289. callback(-1);
  3290. };
  3291. var getRequest = transaction.objectStore("versions").get(url);
  3292. getRequest.onsuccess = function (event) {
  3293. version = (event.target).result;
  3294. };
  3295. getRequest.onerror = function (event) {
  3296. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3297. callback(-1);
  3298. };
  3299. }
  3300. catch (ex) {
  3301. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3302. callback(-1);
  3303. }
  3304. }
  3305. else {
  3306. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3307. callback(-1);
  3308. }
  3309. };
  3310. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3311. var _this = this;
  3312. if (this.isSupported && !this.hasReachedQuota) {
  3313. try {
  3314. // Open a transaction to the database
  3315. var transaction = this.db.transaction(["versions"], "readwrite");
  3316. // the transaction could abort because of a QuotaExceededError error
  3317. transaction.onabort = function (event) {
  3318. try {
  3319. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3320. _this.hasReachedQuota = true;
  3321. }
  3322. }
  3323. catch (ex) { }
  3324. callback(-1);
  3325. };
  3326. transaction.oncomplete = function (event) {
  3327. callback(_this.manifestVersionFound);
  3328. };
  3329. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3330. // Put the scene into the database
  3331. var addRequest = transaction.objectStore("versions").put(newVersion);
  3332. addRequest.onsuccess = function (event) {
  3333. };
  3334. addRequest.onerror = function (event) {
  3335. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3336. };
  3337. }
  3338. catch (ex) {
  3339. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3340. callback(-1);
  3341. }
  3342. }
  3343. else {
  3344. callback(-1);
  3345. }
  3346. };
  3347. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3348. var _this = this;
  3349. var completeUrl = Database.ReturnFullUrlLocation(url);
  3350. var saveAndLoadFile = function (event) {
  3351. // the scene is not yet in the DB, let's try to save it
  3352. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3353. };
  3354. this._checkVersionFromDB(completeUrl, function (version) {
  3355. if (version !== -1) {
  3356. if (!_this.mustUpdateRessources) {
  3357. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3358. }
  3359. else {
  3360. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3361. }
  3362. }
  3363. else {
  3364. errorCallback();
  3365. }
  3366. });
  3367. };
  3368. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3369. if (this.isSupported) {
  3370. var targetStore;
  3371. if (url.indexOf(".babylon") !== -1) {
  3372. targetStore = "scenes";
  3373. }
  3374. else {
  3375. targetStore = "textures";
  3376. }
  3377. var file;
  3378. var transaction = this.db.transaction([targetStore]);
  3379. transaction.oncomplete = function (event) {
  3380. if (file) {
  3381. callback(file.data);
  3382. }
  3383. else {
  3384. notInDBCallback();
  3385. }
  3386. };
  3387. transaction.onabort = function (event) {
  3388. notInDBCallback();
  3389. };
  3390. var getRequest = transaction.objectStore(targetStore).get(url);
  3391. getRequest.onsuccess = function (event) {
  3392. file = (event.target).result;
  3393. };
  3394. getRequest.onerror = function (event) {
  3395. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3396. notInDBCallback();
  3397. };
  3398. }
  3399. else {
  3400. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3401. callback();
  3402. }
  3403. };
  3404. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3405. var _this = this;
  3406. if (this.isSupported) {
  3407. var targetStore;
  3408. if (url.indexOf(".babylon") !== -1) {
  3409. targetStore = "scenes";
  3410. }
  3411. else {
  3412. targetStore = "textures";
  3413. }
  3414. // Create XHR
  3415. var xhr = new XMLHttpRequest(), fileData;
  3416. xhr.open("GET", url, true);
  3417. if (useArrayBuffer) {
  3418. xhr.responseType = "arraybuffer";
  3419. }
  3420. xhr.onprogress = progressCallback;
  3421. xhr.addEventListener("load", function () {
  3422. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3423. // Blob as response (XHR2)
  3424. //fileData = xhr.responseText;
  3425. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3426. if (!_this.hasReachedQuota) {
  3427. // Open a transaction to the database
  3428. var transaction = _this.db.transaction([targetStore], "readwrite");
  3429. // the transaction could abort because of a QuotaExceededError error
  3430. transaction.onabort = function (event) {
  3431. try {
  3432. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3433. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3434. this.hasReachedQuota = true;
  3435. }
  3436. }
  3437. catch (ex) { }
  3438. callback(fileData);
  3439. };
  3440. transaction.oncomplete = function (event) {
  3441. callback(fileData);
  3442. };
  3443. var newFile;
  3444. if (targetStore === "scenes") {
  3445. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3446. }
  3447. else {
  3448. newFile = { textureUrl: url, data: fileData };
  3449. }
  3450. try {
  3451. // Put the scene into the database
  3452. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3453. addRequest.onsuccess = function (event) {
  3454. };
  3455. addRequest.onerror = function (event) {
  3456. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3457. };
  3458. }
  3459. catch (ex) {
  3460. callback(fileData);
  3461. }
  3462. }
  3463. else {
  3464. callback(fileData);
  3465. }
  3466. }
  3467. else {
  3468. callback();
  3469. }
  3470. }, false);
  3471. xhr.addEventListener("error", function (event) {
  3472. BABYLON.Tools.Error("error on XHR request.");
  3473. callback();
  3474. }, false);
  3475. xhr.send();
  3476. }
  3477. else {
  3478. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3479. callback();
  3480. }
  3481. };
  3482. Database.isUASupportingBlobStorage = true;
  3483. Database.parseURL = function (url) {
  3484. var a = document.createElement('a');
  3485. a.href = url;
  3486. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3487. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3488. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3489. return absLocation;
  3490. };
  3491. Database.ReturnFullUrlLocation = function (url) {
  3492. if (url.indexOf("http:/") === -1) {
  3493. return (BABYLON.Database.parseURL(window.location.href) + url);
  3494. }
  3495. else {
  3496. return url;
  3497. }
  3498. };
  3499. return Database;
  3500. })();
  3501. BABYLON.Database = Database;
  3502. })(BABYLON || (BABYLON = {}));
  3503. //# sourceMappingURL=babylon.database.js.map
  3504. var BABYLON;
  3505. (function (BABYLON) {
  3506. var Internals;
  3507. (function (Internals) {
  3508. /*
  3509. * Based on jsTGALoader - Javascript loader for TGA file
  3510. * By Vincent Thibault
  3511. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3512. */
  3513. var TGATools = (function () {
  3514. function TGATools() {
  3515. }
  3516. TGATools.GetTGAHeader = function (data) {
  3517. var offset = 0;
  3518. var header = {
  3519. id_length: data[offset++],
  3520. colormap_type: data[offset++],
  3521. image_type: data[offset++],
  3522. colormap_index: data[offset++] | data[offset++] << 8,
  3523. colormap_length: data[offset++] | data[offset++] << 8,
  3524. colormap_size: data[offset++],
  3525. origin: [
  3526. data[offset++] | data[offset++] << 8,
  3527. data[offset++] | data[offset++] << 8
  3528. ],
  3529. width: data[offset++] | data[offset++] << 8,
  3530. height: data[offset++] | data[offset++] << 8,
  3531. pixel_size: data[offset++],
  3532. flags: data[offset++]
  3533. };
  3534. return header;
  3535. };
  3536. TGATools.UploadContent = function (gl, data) {
  3537. // Not enough data to contain header ?
  3538. if (data.length < 19) {
  3539. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3540. return;
  3541. }
  3542. // Read Header
  3543. var offset = 18;
  3544. var header = TGATools.GetTGAHeader(data);
  3545. // Assume it's a valid Targa file.
  3546. if (header.id_length + offset > data.length) {
  3547. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3548. return;
  3549. }
  3550. // Skip not needed data
  3551. offset += header.id_length;
  3552. var use_rle = false;
  3553. var use_pal = false;
  3554. var use_rgb = false;
  3555. var use_grey = false;
  3556. // Get some informations.
  3557. switch (header.image_type) {
  3558. case TGATools._TYPE_RLE_INDEXED:
  3559. use_rle = true;
  3560. case TGATools._TYPE_INDEXED:
  3561. use_pal = true;
  3562. break;
  3563. case TGATools._TYPE_RLE_RGB:
  3564. use_rle = true;
  3565. case TGATools._TYPE_RGB:
  3566. use_rgb = true;
  3567. break;
  3568. case TGATools._TYPE_RLE_GREY:
  3569. use_rle = true;
  3570. case TGATools._TYPE_GREY:
  3571. use_grey = true;
  3572. break;
  3573. }
  3574. var pixel_data;
  3575. var numAlphaBits = header.flags & 0xf;
  3576. var pixel_size = header.pixel_size >> 3;
  3577. var pixel_total = header.width * header.height * pixel_size;
  3578. // Read palettes
  3579. var palettes;
  3580. if (use_pal) {
  3581. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3582. }
  3583. // Read LRE
  3584. if (use_rle) {
  3585. pixel_data = new Uint8Array(pixel_total);
  3586. var c, count, i;
  3587. var localOffset = 0;
  3588. var pixels = new Uint8Array(pixel_size);
  3589. while (offset < pixel_total && localOffset < pixel_total) {
  3590. c = data[offset++];
  3591. count = (c & 0x7f) + 1;
  3592. // RLE pixels
  3593. if (c & 0x80) {
  3594. // Bind pixel tmp array
  3595. for (i = 0; i < pixel_size; ++i) {
  3596. pixels[i] = data[offset++];
  3597. }
  3598. // Copy pixel array
  3599. for (i = 0; i < count; ++i) {
  3600. pixel_data.set(pixels, localOffset + i * pixel_size);
  3601. }
  3602. localOffset += pixel_size * count;
  3603. }
  3604. else {
  3605. count *= pixel_size;
  3606. for (i = 0; i < count; ++i) {
  3607. pixel_data[localOffset + i] = data[offset++];
  3608. }
  3609. localOffset += count;
  3610. }
  3611. }
  3612. }
  3613. else {
  3614. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3615. }
  3616. // Load to texture
  3617. var x_start, y_start, x_step, y_step, y_end, x_end;
  3618. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3619. default:
  3620. case TGATools._ORIGIN_UL:
  3621. x_start = 0;
  3622. x_step = 1;
  3623. x_end = header.width;
  3624. y_start = 0;
  3625. y_step = 1;
  3626. y_end = header.height;
  3627. break;
  3628. case TGATools._ORIGIN_BL:
  3629. x_start = 0;
  3630. x_step = 1;
  3631. x_end = header.width;
  3632. y_start = header.height - 1;
  3633. y_step = -1;
  3634. y_end = -1;
  3635. break;
  3636. case TGATools._ORIGIN_UR:
  3637. x_start = header.width - 1;
  3638. x_step = -1;
  3639. x_end = -1;
  3640. y_start = 0;
  3641. y_step = 1;
  3642. y_end = header.height;
  3643. break;
  3644. case TGATools._ORIGIN_BR:
  3645. x_start = header.width - 1;
  3646. x_step = -1;
  3647. x_end = -1;
  3648. y_start = header.height - 1;
  3649. y_step = -1;
  3650. y_end = -1;
  3651. break;
  3652. }
  3653. // Load the specify method
  3654. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3655. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3656. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3657. };
  3658. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3659. var image = pixel_data, colormap = palettes;
  3660. var width = header.width, height = header.height;
  3661. var color, i = 0, x, y;
  3662. var imageData = new Uint8Array(width * height * 4);
  3663. for (y = y_start; y !== y_end; y += y_step) {
  3664. for (x = x_start; x !== x_end; x += x_step, i++) {
  3665. color = image[i];
  3666. imageData[(x + width * y) * 4 + 3] = 255;
  3667. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3668. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3669. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3670. }
  3671. }
  3672. return imageData;
  3673. };
  3674. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3675. var image = pixel_data;
  3676. var width = header.width, height = header.height;
  3677. var color, i = 0, x, y;
  3678. var imageData = new Uint8Array(width * height * 4);
  3679. for (y = y_start; y !== y_end; y += y_step) {
  3680. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3681. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3682. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3683. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3684. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3685. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3686. }
  3687. }
  3688. return imageData;
  3689. };
  3690. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3691. var image = pixel_data;
  3692. var width = header.width, height = header.height;
  3693. var i = 0, x, y;
  3694. var imageData = new Uint8Array(width * height * 4);
  3695. for (y = y_start; y !== y_end; y += y_step) {
  3696. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3697. imageData[(x + width * y) * 4 + 3] = 255;
  3698. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3699. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3700. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3701. }
  3702. }
  3703. return imageData;
  3704. };
  3705. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3706. var image = pixel_data;
  3707. var width = header.width, height = header.height;
  3708. var i = 0, x, y;
  3709. var imageData = new Uint8Array(width * height * 4);
  3710. for (y = y_start; y !== y_end; y += y_step) {
  3711. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3712. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3713. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3714. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3715. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3716. }
  3717. }
  3718. return imageData;
  3719. };
  3720. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3721. var image = pixel_data;
  3722. var width = header.width, height = header.height;
  3723. var color, i = 0, x, y;
  3724. var imageData = new Uint8Array(width * height * 4);
  3725. for (y = y_start; y !== y_end; y += y_step) {
  3726. for (x = x_start; x !== x_end; x += x_step, i++) {
  3727. color = image[i];
  3728. imageData[(x + width * y) * 4 + 0] = color;
  3729. imageData[(x + width * y) * 4 + 1] = color;
  3730. imageData[(x + width * y) * 4 + 2] = color;
  3731. imageData[(x + width * y) * 4 + 3] = 255;
  3732. }
  3733. }
  3734. return imageData;
  3735. };
  3736. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3737. var image = pixel_data;
  3738. var width = header.width, height = header.height;
  3739. var i = 0, x, y;
  3740. var imageData = new Uint8Array(width * height * 4);
  3741. for (y = y_start; y !== y_end; y += y_step) {
  3742. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3743. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3744. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3745. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3746. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3747. }
  3748. }
  3749. return imageData;
  3750. };
  3751. TGATools._TYPE_NO_DATA = 0;
  3752. TGATools._TYPE_INDEXED = 1;
  3753. TGATools._TYPE_RGB = 2;
  3754. TGATools._TYPE_GREY = 3;
  3755. TGATools._TYPE_RLE_INDEXED = 9;
  3756. TGATools._TYPE_RLE_RGB = 10;
  3757. TGATools._TYPE_RLE_GREY = 11;
  3758. TGATools._ORIGIN_MASK = 0x30;
  3759. TGATools._ORIGIN_SHIFT = 0x04;
  3760. TGATools._ORIGIN_BL = 0x00;
  3761. TGATools._ORIGIN_BR = 0x01;
  3762. TGATools._ORIGIN_UL = 0x02;
  3763. TGATools._ORIGIN_UR = 0x03;
  3764. return TGATools;
  3765. })();
  3766. Internals.TGATools = TGATools;
  3767. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3768. })(BABYLON || (BABYLON = {}));
  3769. //# sourceMappingURL=babylon.tools.tga.js.map
  3770. var BABYLON;
  3771. (function (BABYLON) {
  3772. var Internals;
  3773. (function (Internals) {
  3774. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3775. // All values and structures referenced from:
  3776. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3777. var DDS_MAGIC = 0x20534444;
  3778. 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;
  3779. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3780. 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;
  3781. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3782. function FourCCToInt32(value) {
  3783. return value.charCodeAt(0) +
  3784. (value.charCodeAt(1) << 8) +
  3785. (value.charCodeAt(2) << 16) +
  3786. (value.charCodeAt(3) << 24);
  3787. }
  3788. function Int32ToFourCC(value) {
  3789. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3790. }
  3791. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3792. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3793. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3794. var headerLengthInt = 31; // The header length in 32 bit ints
  3795. // Offsets into the header array
  3796. var off_magic = 0;
  3797. var off_size = 1;
  3798. var off_flags = 2;
  3799. var off_height = 3;
  3800. var off_width = 4;
  3801. var off_mipmapCount = 7;
  3802. var off_pfFlags = 20;
  3803. var off_pfFourCC = 21;
  3804. var off_RGBbpp = 22;
  3805. var off_RMask = 23;
  3806. var off_GMask = 24;
  3807. var off_BMask = 25;
  3808. var off_AMask = 26;
  3809. var off_caps1 = 27;
  3810. var off_caps2 = 28;
  3811. ;
  3812. var DDSTools = (function () {
  3813. function DDSTools() {
  3814. }
  3815. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3816. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3817. var mipmapCount = 1;
  3818. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3819. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3820. }
  3821. return {
  3822. width: header[off_width],
  3823. height: header[off_height],
  3824. mipmapCount: mipmapCount,
  3825. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3826. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3827. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3828. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3829. };
  3830. };
  3831. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3832. var byteArray = new Uint8Array(dataLength);
  3833. var srcData = new Uint8Array(arrayBuffer);
  3834. var index = 0;
  3835. for (var y = height - 1; y >= 0; y--) {
  3836. for (var x = 0; x < width; x++) {
  3837. var srcPos = dataOffset + (x + y * width) * 4;
  3838. byteArray[index + 2] = srcData[srcPos];
  3839. byteArray[index + 1] = srcData[srcPos + 1];
  3840. byteArray[index] = srcData[srcPos + 2];
  3841. byteArray[index + 3] = srcData[srcPos + 3];
  3842. index += 4;
  3843. }
  3844. }
  3845. return byteArray;
  3846. };
  3847. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3848. var byteArray = new Uint8Array(dataLength);
  3849. var srcData = new Uint8Array(arrayBuffer);
  3850. var index = 0;
  3851. for (var y = height - 1; y >= 0; y--) {
  3852. for (var x = 0; x < width; x++) {
  3853. var srcPos = dataOffset + (x + y * width) * 3;
  3854. byteArray[index + 2] = srcData[srcPos];
  3855. byteArray[index + 1] = srcData[srcPos + 1];
  3856. byteArray[index] = srcData[srcPos + 2];
  3857. index += 3;
  3858. }
  3859. }
  3860. return byteArray;
  3861. };
  3862. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3863. var byteArray = new Uint8Array(dataLength);
  3864. var srcData = new Uint8Array(arrayBuffer);
  3865. var index = 0;
  3866. for (var y = height - 1; y >= 0; y--) {
  3867. for (var x = 0; x < width; x++) {
  3868. var srcPos = dataOffset + (x + y * width);
  3869. byteArray[index] = srcData[srcPos];
  3870. index++;
  3871. }
  3872. }
  3873. return byteArray;
  3874. };
  3875. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3876. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3877. if (header[off_magic] != DDS_MAGIC) {
  3878. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3879. return;
  3880. }
  3881. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3882. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3883. return;
  3884. }
  3885. if (info.isFourCC) {
  3886. fourCC = header[off_pfFourCC];
  3887. switch (fourCC) {
  3888. case FOURCC_DXT1:
  3889. blockBytes = 8;
  3890. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3891. break;
  3892. case FOURCC_DXT3:
  3893. blockBytes = 16;
  3894. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3895. break;
  3896. case FOURCC_DXT5:
  3897. blockBytes = 16;
  3898. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3899. break;
  3900. default:
  3901. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  3902. return;
  3903. }
  3904. }
  3905. mipmapCount = 1;
  3906. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  3907. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3908. }
  3909. var bpp = header[off_RGBbpp];
  3910. for (var face = 0; face < faces; face++) {
  3911. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  3912. width = header[off_width];
  3913. height = header[off_height];
  3914. dataOffset = header[off_size] + 4;
  3915. for (i = 0; i < mipmapCount; ++i) {
  3916. if (info.isRGB) {
  3917. if (bpp == 24) {
  3918. dataLength = width * height * 3;
  3919. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3920. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  3921. }
  3922. else {
  3923. dataLength = width * height * 4;
  3924. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3925. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  3926. }
  3927. }
  3928. else if (info.isLuminance) {
  3929. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  3930. var unpaddedRowSize = width;
  3931. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  3932. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  3933. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3934. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  3935. }
  3936. else {
  3937. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  3938. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  3939. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  3940. }
  3941. dataOffset += dataLength;
  3942. width *= 0.5;
  3943. height *= 0.5;
  3944. width = Math.max(1.0, width);
  3945. height = Math.max(1.0, height);
  3946. }
  3947. }
  3948. };
  3949. return DDSTools;
  3950. })();
  3951. Internals.DDSTools = DDSTools;
  3952. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3953. })(BABYLON || (BABYLON = {}));
  3954. //# sourceMappingURL=babylon.tools.dds.js.map
  3955. var BABYLON;
  3956. (function (BABYLON) {
  3957. var SmartArray = (function () {
  3958. function SmartArray(capacity) {
  3959. this.length = 0;
  3960. this._duplicateId = 0;
  3961. this.data = new Array(capacity);
  3962. this._id = SmartArray._GlobalId++;
  3963. }
  3964. SmartArray.prototype.push = function (value) {
  3965. this.data[this.length++] = value;
  3966. if (this.length > this.data.length) {
  3967. this.data.length *= 2;
  3968. }
  3969. if (!value.__smartArrayFlags) {
  3970. value.__smartArrayFlags = {};
  3971. }
  3972. value.__smartArrayFlags[this._id] = this._duplicateId;
  3973. };
  3974. SmartArray.prototype.pushNoDuplicate = function (value) {
  3975. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3976. return;
  3977. }
  3978. this.push(value);
  3979. };
  3980. SmartArray.prototype.sort = function (compareFn) {
  3981. this.data.sort(compareFn);
  3982. };
  3983. SmartArray.prototype.reset = function () {
  3984. this.length = 0;
  3985. this._duplicateId++;
  3986. };
  3987. SmartArray.prototype.concat = function (array) {
  3988. if (array.length === 0) {
  3989. return;
  3990. }
  3991. if (this.length + array.length > this.data.length) {
  3992. this.data.length = (this.length + array.length) * 2;
  3993. }
  3994. for (var index = 0; index < array.length; index++) {
  3995. this.data[this.length++] = (array.data || array)[index];
  3996. }
  3997. };
  3998. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3999. if (array.length === 0) {
  4000. return;
  4001. }
  4002. if (this.length + array.length > this.data.length) {
  4003. this.data.length = (this.length + array.length) * 2;
  4004. }
  4005. for (var index = 0; index < array.length; index++) {
  4006. var item = (array.data || array)[index];
  4007. this.pushNoDuplicate(item);
  4008. }
  4009. };
  4010. SmartArray.prototype.indexOf = function (value) {
  4011. var position = this.data.indexOf(value);
  4012. if (position >= this.length) {
  4013. return -1;
  4014. }
  4015. return position;
  4016. };
  4017. // Statics
  4018. SmartArray._GlobalId = 0;
  4019. return SmartArray;
  4020. })();
  4021. BABYLON.SmartArray = SmartArray;
  4022. })(BABYLON || (BABYLON = {}));
  4023. //# sourceMappingURL=babylon.smartArray.js.map
  4024. var BABYLON;
  4025. (function (BABYLON) {
  4026. var SmartCollection = (function () {
  4027. function SmartCollection(capacity) {
  4028. if (capacity === void 0) { capacity = 10; }
  4029. this.count = 0;
  4030. this._initialCapacity = capacity;
  4031. this.items = {};
  4032. this._keys = new Array(this._initialCapacity);
  4033. }
  4034. SmartCollection.prototype.add = function (key, item) {
  4035. if (this.items[key] != undefined) {
  4036. return -1;
  4037. }
  4038. this.items[key] = item;
  4039. //literal keys are always strings, but we keep source type of key in _keys array
  4040. this._keys[this.count++] = key;
  4041. if (this.count > this._keys.length) {
  4042. this._keys.length *= 2;
  4043. }
  4044. return this.count;
  4045. };
  4046. SmartCollection.prototype.remove = function (key) {
  4047. if (this.items[key] == undefined) {
  4048. return -1;
  4049. }
  4050. return this.removeItemOfIndex(this.indexOf(key));
  4051. };
  4052. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4053. if (index < this.count && index > -1) {
  4054. delete this.items[this._keys[index]];
  4055. //here, shifting by hand is better optimised than .splice
  4056. while (index < this.count) {
  4057. this._keys[index] = this._keys[index + 1];
  4058. index++;
  4059. }
  4060. }
  4061. else {
  4062. return -1;
  4063. }
  4064. return --this.count;
  4065. };
  4066. SmartCollection.prototype.indexOf = function (key) {
  4067. for (var i = 0; i !== this.count; i++) {
  4068. if (this._keys[i] === key) {
  4069. return i;
  4070. }
  4071. }
  4072. return -1;
  4073. };
  4074. SmartCollection.prototype.item = function (key) {
  4075. return this.items[key];
  4076. };
  4077. SmartCollection.prototype.getAllKeys = function () {
  4078. if (this.count > 0) {
  4079. var keys = new Array(this.count);
  4080. for (var i = 0; i < this.count; i++) {
  4081. keys[i] = this._keys[i];
  4082. }
  4083. return keys;
  4084. }
  4085. else {
  4086. return undefined;
  4087. }
  4088. };
  4089. SmartCollection.prototype.getKeyByIndex = function (index) {
  4090. if (index < this.count && index > -1) {
  4091. return this._keys[index];
  4092. }
  4093. else {
  4094. return undefined;
  4095. }
  4096. };
  4097. SmartCollection.prototype.getItemByIndex = function (index) {
  4098. if (index < this.count && index > -1) {
  4099. return this.items[this._keys[index]];
  4100. }
  4101. else {
  4102. return undefined;
  4103. }
  4104. };
  4105. SmartCollection.prototype.empty = function () {
  4106. if (this.count > 0) {
  4107. this.count = 0;
  4108. this.items = {};
  4109. this._keys = new Array(this._initialCapacity);
  4110. }
  4111. };
  4112. SmartCollection.prototype.forEach = function (block) {
  4113. var key;
  4114. for (key in this.items) {
  4115. if (this.items.hasOwnProperty(key)) {
  4116. block(this.items[key]);
  4117. }
  4118. }
  4119. };
  4120. return SmartCollection;
  4121. })();
  4122. BABYLON.SmartCollection = SmartCollection;
  4123. })(BABYLON || (BABYLON = {}));
  4124. //# sourceMappingURL=babylon.smartCollection.js.map
  4125. var BABYLON;
  4126. (function (BABYLON) {
  4127. // Screenshots
  4128. var screenshotCanvas;
  4129. var cloneValue = function (source, destinationObject) {
  4130. if (!source)
  4131. return null;
  4132. if (source instanceof BABYLON.Mesh) {
  4133. return null;
  4134. }
  4135. if (source instanceof BABYLON.SubMesh) {
  4136. return source.clone(destinationObject);
  4137. }
  4138. else if (source.clone) {
  4139. return source.clone();
  4140. }
  4141. return null;
  4142. };
  4143. var Tools = (function () {
  4144. function Tools() {
  4145. }
  4146. Tools.SetImmediate = function (action) {
  4147. if (window.setImmediate) {
  4148. window.setImmediate(action);
  4149. }
  4150. else {
  4151. setTimeout(action, 1);
  4152. }
  4153. };
  4154. Tools.IsExponantOfTwo = function (value) {
  4155. var count = 1;
  4156. do {
  4157. count *= 2;
  4158. } while (count < value);
  4159. return count === value;
  4160. };
  4161. ;
  4162. Tools.GetExponantOfTwo = function (value, max) {
  4163. var count = 1;
  4164. do {
  4165. count *= 2;
  4166. } while (count < value);
  4167. if (count > max)
  4168. count = max;
  4169. return count;
  4170. };
  4171. ;
  4172. Tools.GetFilename = function (path) {
  4173. var index = path.lastIndexOf("/");
  4174. if (index < 0)
  4175. return path;
  4176. return path.substring(index + 1);
  4177. };
  4178. Tools.GetDOMTextContent = function (element) {
  4179. var result = "";
  4180. var child = element.firstChild;
  4181. while (child) {
  4182. if (child.nodeType === 3) {
  4183. result += child.textContent;
  4184. }
  4185. child = child.nextSibling;
  4186. }
  4187. return result;
  4188. };
  4189. Tools.ToDegrees = function (angle) {
  4190. return angle * 180 / Math.PI;
  4191. };
  4192. Tools.ToRadians = function (angle) {
  4193. return angle * Math.PI / 180;
  4194. };
  4195. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4196. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4197. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4198. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4199. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4200. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4201. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4202. }
  4203. return {
  4204. minimum: minimum,
  4205. maximum: maximum
  4206. };
  4207. };
  4208. Tools.ExtractMinAndMax = function (positions, start, count) {
  4209. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4210. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4211. for (var index = start; index < start + count; index++) {
  4212. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4213. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4214. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4215. }
  4216. return {
  4217. minimum: minimum,
  4218. maximum: maximum
  4219. };
  4220. };
  4221. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4222. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4223. return undefined;
  4224. return Array.isArray(obj) ? obj : [obj];
  4225. };
  4226. // Misc.
  4227. Tools.GetPointerPrefix = function () {
  4228. var eventPrefix = "pointer";
  4229. // Check if hand.js is referenced or if the browser natively supports pointer events
  4230. if (!navigator.pointerEnabled) {
  4231. eventPrefix = "mouse";
  4232. }
  4233. return eventPrefix;
  4234. };
  4235. Tools.QueueNewFrame = function (func) {
  4236. if (window.requestAnimationFrame)
  4237. window.requestAnimationFrame(func);
  4238. else if (window.msRequestAnimationFrame)
  4239. window.msRequestAnimationFrame(func);
  4240. else if (window.webkitRequestAnimationFrame)
  4241. window.webkitRequestAnimationFrame(func);
  4242. else if (window.mozRequestAnimationFrame)
  4243. window.mozRequestAnimationFrame(func);
  4244. else if (window.oRequestAnimationFrame)
  4245. window.oRequestAnimationFrame(func);
  4246. else {
  4247. window.setTimeout(func, 16);
  4248. }
  4249. };
  4250. Tools.RequestFullscreen = function (element) {
  4251. if (element.requestFullscreen)
  4252. element.requestFullscreen();
  4253. else if (element.msRequestFullscreen)
  4254. element.msRequestFullscreen();
  4255. else if (element.webkitRequestFullscreen)
  4256. element.webkitRequestFullscreen();
  4257. else if (element.mozRequestFullScreen)
  4258. element.mozRequestFullScreen();
  4259. };
  4260. Tools.ExitFullscreen = function () {
  4261. if (document.exitFullscreen) {
  4262. document.exitFullscreen();
  4263. }
  4264. else if (document.mozCancelFullScreen) {
  4265. document.mozCancelFullScreen();
  4266. }
  4267. else if (document.webkitCancelFullScreen) {
  4268. document.webkitCancelFullScreen();
  4269. }
  4270. else if (document.msCancelFullScreen) {
  4271. document.msCancelFullScreen();
  4272. }
  4273. };
  4274. // External files
  4275. Tools.CleanUrl = function (url) {
  4276. url = url.replace(/#/mg, "%23");
  4277. return url;
  4278. };
  4279. Tools.LoadImage = function (url, onload, onerror, database) {
  4280. url = Tools.CleanUrl(url);
  4281. var img = new Image();
  4282. if (url.substr(0, 5) !== "data:")
  4283. img.crossOrigin = 'anonymous';
  4284. img.onload = function () {
  4285. onload(img);
  4286. };
  4287. img.onerror = function (err) {
  4288. onerror(img, err);
  4289. };
  4290. var noIndexedDB = function () {
  4291. img.src = url;
  4292. };
  4293. var loadFromIndexedDB = function () {
  4294. database.loadImageFromDB(url, img);
  4295. };
  4296. //ANY database to do!
  4297. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  4298. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4299. }
  4300. else {
  4301. if (url.indexOf("file:") === -1) {
  4302. noIndexedDB();
  4303. }
  4304. else {
  4305. try {
  4306. var textureName = url.substring(5);
  4307. var blobURL;
  4308. try {
  4309. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4310. }
  4311. catch (ex) {
  4312. // Chrome doesn't support oneTimeOnly parameter
  4313. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4314. }
  4315. img.src = blobURL;
  4316. }
  4317. catch (e) {
  4318. Tools.Log("Error while trying to load texture: " + textureName);
  4319. img.src = null;
  4320. }
  4321. }
  4322. }
  4323. return img;
  4324. };
  4325. //ANY
  4326. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4327. url = Tools.CleanUrl(url);
  4328. var noIndexedDB = function () {
  4329. var request = new XMLHttpRequest();
  4330. var loadUrl = Tools.BaseUrl + url;
  4331. request.open('GET', loadUrl, true);
  4332. if (useArrayBuffer) {
  4333. request.responseType = "arraybuffer";
  4334. }
  4335. request.onprogress = progressCallBack;
  4336. request.onreadystatechange = function () {
  4337. if (request.readyState === 4) {
  4338. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4339. callback(!useArrayBuffer ? request.responseText : request.response);
  4340. }
  4341. else {
  4342. if (onError) {
  4343. onError();
  4344. }
  4345. else {
  4346. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4347. }
  4348. }
  4349. }
  4350. };
  4351. request.send(null);
  4352. };
  4353. var loadFromIndexedDB = function () {
  4354. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4355. };
  4356. if (url.indexOf("file:") !== -1) {
  4357. var fileName = url.substring(5);
  4358. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4359. }
  4360. else {
  4361. // Caching all files
  4362. if (database && database.enableSceneOffline) {
  4363. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4364. }
  4365. else {
  4366. noIndexedDB();
  4367. }
  4368. }
  4369. };
  4370. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4371. var reader = new FileReader();
  4372. reader.onload = function (e) {
  4373. //target doesn't have result from ts 1.3
  4374. callback(e.target['result']);
  4375. };
  4376. reader.onprogress = progressCallback;
  4377. reader.readAsDataURL(fileToLoad);
  4378. };
  4379. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4380. var reader = new FileReader();
  4381. reader.onerror = function (e) {
  4382. Tools.Log("Error while reading file: " + fileToLoad.name);
  4383. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  4384. };
  4385. reader.onload = function (e) {
  4386. //target doesn't have result from ts 1.3
  4387. callback(e.target['result']);
  4388. };
  4389. reader.onprogress = progressCallBack;
  4390. if (!useArrayBuffer) {
  4391. // Asynchronous read
  4392. reader.readAsText(fileToLoad);
  4393. }
  4394. else {
  4395. reader.readAsArrayBuffer(fileToLoad);
  4396. }
  4397. };
  4398. // Misc.
  4399. Tools.Clamp = function (value, min, max) {
  4400. if (min === void 0) { min = 0; }
  4401. if (max === void 0) { max = 1; }
  4402. return Math.min(max, Math.max(min, value));
  4403. };
  4404. // Returns -1 when value is a negative number and
  4405. // +1 when value is a positive number.
  4406. Tools.Sign = function (value) {
  4407. value = +value; // convert to a number
  4408. if (value === 0 || isNaN(value))
  4409. return value;
  4410. return value > 0 ? 1 : -1;
  4411. };
  4412. Tools.Format = function (value, decimals) {
  4413. if (decimals === void 0) { decimals = 2; }
  4414. return value.toFixed(decimals);
  4415. };
  4416. Tools.CheckExtends = function (v, min, max) {
  4417. if (v.x < min.x)
  4418. min.x = v.x;
  4419. if (v.y < min.y)
  4420. min.y = v.y;
  4421. if (v.z < min.z)
  4422. min.z = v.z;
  4423. if (v.x > max.x)
  4424. max.x = v.x;
  4425. if (v.y > max.y)
  4426. max.y = v.y;
  4427. if (v.z > max.z)
  4428. max.z = v.z;
  4429. };
  4430. Tools.WithinEpsilon = function (a, b, epsilon) {
  4431. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4432. var num = a - b;
  4433. return -epsilon <= num && num <= epsilon;
  4434. };
  4435. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4436. for (var prop in source) {
  4437. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4438. continue;
  4439. }
  4440. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4441. continue;
  4442. }
  4443. var sourceValue = source[prop];
  4444. var typeOfSourceValue = typeof sourceValue;
  4445. if (typeOfSourceValue === "function") {
  4446. continue;
  4447. }
  4448. if (typeOfSourceValue === "object") {
  4449. if (sourceValue instanceof Array) {
  4450. destination[prop] = [];
  4451. if (sourceValue.length > 0) {
  4452. if (typeof sourceValue[0] == "object") {
  4453. for (var index = 0; index < sourceValue.length; index++) {
  4454. var clonedValue = cloneValue(sourceValue[index], destination);
  4455. if (destination[prop].indexOf(clonedValue) === -1) {
  4456. destination[prop].push(clonedValue);
  4457. }
  4458. }
  4459. }
  4460. else {
  4461. destination[prop] = sourceValue.slice(0);
  4462. }
  4463. }
  4464. }
  4465. else {
  4466. destination[prop] = cloneValue(sourceValue, destination);
  4467. }
  4468. }
  4469. else {
  4470. destination[prop] = sourceValue;
  4471. }
  4472. }
  4473. };
  4474. Tools.IsEmpty = function (obj) {
  4475. for (var i in obj) {
  4476. return false;
  4477. }
  4478. return true;
  4479. };
  4480. Tools.RegisterTopRootEvents = function (events) {
  4481. for (var index = 0; index < events.length; index++) {
  4482. var event = events[index];
  4483. window.addEventListener(event.name, event.handler, false);
  4484. try {
  4485. if (window.parent) {
  4486. window.parent.addEventListener(event.name, event.handler, false);
  4487. }
  4488. }
  4489. catch (e) {
  4490. }
  4491. }
  4492. };
  4493. Tools.UnregisterTopRootEvents = function (events) {
  4494. for (var index = 0; index < events.length; index++) {
  4495. var event = events[index];
  4496. window.removeEventListener(event.name, event.handler);
  4497. try {
  4498. if (window.parent) {
  4499. window.parent.removeEventListener(event.name, event.handler);
  4500. }
  4501. }
  4502. catch (e) {
  4503. }
  4504. }
  4505. };
  4506. Tools.DumpFramebuffer = function (width, height, engine) {
  4507. // Read the contents of the framebuffer
  4508. var numberOfChannelsByLine = width * 4;
  4509. var halfHeight = height / 2;
  4510. //Reading datas from WebGL
  4511. var data = engine.readPixels(0, 0, width, height);
  4512. //To flip image on Y axis.
  4513. for (var i = 0; i < halfHeight; i++) {
  4514. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4515. var currentCell = j + i * numberOfChannelsByLine;
  4516. var targetLine = height - i - 1;
  4517. var targetCell = j + targetLine * numberOfChannelsByLine;
  4518. var temp = data[currentCell];
  4519. data[currentCell] = data[targetCell];
  4520. data[targetCell] = temp;
  4521. }
  4522. }
  4523. // Create a 2D canvas to store the result
  4524. if (!screenshotCanvas) {
  4525. screenshotCanvas = document.createElement('canvas');
  4526. }
  4527. screenshotCanvas.width = width;
  4528. screenshotCanvas.height = height;
  4529. var context = screenshotCanvas.getContext('2d');
  4530. // Copy the pixels to a 2D canvas
  4531. var imageData = context.createImageData(width, height);
  4532. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4533. var castData = imageData.data;
  4534. castData.set(data);
  4535. context.putImageData(imageData, 0, 0);
  4536. var base64Image = screenshotCanvas.toDataURL();
  4537. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4538. if (("download" in document.createElement("a"))) {
  4539. var a = window.document.createElement("a");
  4540. a.href = base64Image;
  4541. var date = new Date();
  4542. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4543. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4544. window.document.body.appendChild(a);
  4545. a.addEventListener("click", function () {
  4546. a.parentElement.removeChild(a);
  4547. });
  4548. a.click();
  4549. }
  4550. else {
  4551. var newWindow = window.open("");
  4552. var img = newWindow.document.createElement("img");
  4553. img.src = base64Image;
  4554. newWindow.document.body.appendChild(img);
  4555. }
  4556. };
  4557. Tools.CreateScreenshot = function (engine, camera, size) {
  4558. var width;
  4559. var height;
  4560. var scene = camera.getScene();
  4561. var previousCamera = null;
  4562. if (scene.activeCamera !== camera) {
  4563. previousCamera = scene.activeCamera;
  4564. scene.activeCamera = camera;
  4565. }
  4566. //If a precision value is specified
  4567. if (size.precision) {
  4568. width = Math.round(engine.getRenderWidth() * size.precision);
  4569. height = Math.round(width / engine.getAspectRatio(camera));
  4570. size = { width: width, height: height };
  4571. }
  4572. else if (size.width && size.height) {
  4573. width = size.width;
  4574. height = size.height;
  4575. }
  4576. else if (size.width && !size.height) {
  4577. width = size.width;
  4578. height = Math.round(width / engine.getAspectRatio(camera));
  4579. size = { width: width, height: height };
  4580. }
  4581. else if (size.height && !size.width) {
  4582. height = size.height;
  4583. width = Math.round(height * engine.getAspectRatio(camera));
  4584. size = { width: width, height: height };
  4585. }
  4586. else if (!isNaN(size)) {
  4587. height = size;
  4588. width = size;
  4589. }
  4590. else {
  4591. Tools.Error("Invalid 'size' parameter !");
  4592. return;
  4593. }
  4594. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4595. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4596. texture.renderList = scene.meshes;
  4597. texture.onAfterRender = function () {
  4598. Tools.DumpFramebuffer(width, height, engine);
  4599. };
  4600. scene.incrementRenderId();
  4601. texture.render(true);
  4602. texture.dispose();
  4603. if (previousCamera) {
  4604. scene.activeCamera = previousCamera;
  4605. }
  4606. };
  4607. // XHR response validator for local file scenario
  4608. Tools.ValidateXHRData = function (xhr, dataType) {
  4609. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4610. if (dataType === void 0) { dataType = 7; }
  4611. try {
  4612. if (dataType & 1) {
  4613. if (xhr.responseText && xhr.responseText.length > 0) {
  4614. return true;
  4615. }
  4616. else if (dataType === 1) {
  4617. return false;
  4618. }
  4619. }
  4620. if (dataType & 2) {
  4621. // Check header width and height since there is no "TGA" magic number
  4622. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4623. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4624. return true;
  4625. }
  4626. else if (dataType === 2) {
  4627. return false;
  4628. }
  4629. }
  4630. if (dataType & 4) {
  4631. // Check for the "DDS" magic number
  4632. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4633. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4634. return true;
  4635. }
  4636. else {
  4637. return false;
  4638. }
  4639. }
  4640. }
  4641. catch (e) {
  4642. }
  4643. return false;
  4644. };
  4645. Object.defineProperty(Tools, "NoneLogLevel", {
  4646. get: function () {
  4647. return Tools._NoneLogLevel;
  4648. },
  4649. enumerable: true,
  4650. configurable: true
  4651. });
  4652. Object.defineProperty(Tools, "MessageLogLevel", {
  4653. get: function () {
  4654. return Tools._MessageLogLevel;
  4655. },
  4656. enumerable: true,
  4657. configurable: true
  4658. });
  4659. Object.defineProperty(Tools, "WarningLogLevel", {
  4660. get: function () {
  4661. return Tools._WarningLogLevel;
  4662. },
  4663. enumerable: true,
  4664. configurable: true
  4665. });
  4666. Object.defineProperty(Tools, "ErrorLogLevel", {
  4667. get: function () {
  4668. return Tools._ErrorLogLevel;
  4669. },
  4670. enumerable: true,
  4671. configurable: true
  4672. });
  4673. Object.defineProperty(Tools, "AllLogLevel", {
  4674. get: function () {
  4675. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4676. },
  4677. enumerable: true,
  4678. configurable: true
  4679. });
  4680. Tools._AddLogEntry = function (entry) {
  4681. Tools._LogCache = entry + Tools._LogCache;
  4682. if (Tools.OnNewCacheEntry) {
  4683. Tools.OnNewCacheEntry(entry);
  4684. }
  4685. };
  4686. Tools._FormatMessage = function (message) {
  4687. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4688. var date = new Date();
  4689. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4690. };
  4691. Tools._LogDisabled = function (message) {
  4692. // nothing to do
  4693. };
  4694. Tools._LogEnabled = function (message) {
  4695. var formattedMessage = Tools._FormatMessage(message);
  4696. console.log("BJS - " + formattedMessage);
  4697. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4698. Tools._AddLogEntry(entry);
  4699. };
  4700. Tools._WarnDisabled = function (message) {
  4701. // nothing to do
  4702. };
  4703. Tools._WarnEnabled = function (message) {
  4704. var formattedMessage = Tools._FormatMessage(message);
  4705. console.warn("BJS - " + formattedMessage);
  4706. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4707. Tools._AddLogEntry(entry);
  4708. };
  4709. Tools._ErrorDisabled = function (message) {
  4710. // nothing to do
  4711. };
  4712. Tools._ErrorEnabled = function (message) {
  4713. var formattedMessage = Tools._FormatMessage(message);
  4714. console.error("BJS - " + formattedMessage);
  4715. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4716. Tools._AddLogEntry(entry);
  4717. };
  4718. Object.defineProperty(Tools, "LogCache", {
  4719. get: function () {
  4720. return Tools._LogCache;
  4721. },
  4722. enumerable: true,
  4723. configurable: true
  4724. });
  4725. Object.defineProperty(Tools, "LogLevels", {
  4726. set: function (level) {
  4727. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4728. Tools.Log = Tools._LogEnabled;
  4729. }
  4730. else {
  4731. Tools.Log = Tools._LogDisabled;
  4732. }
  4733. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4734. Tools.Warn = Tools._WarnEnabled;
  4735. }
  4736. else {
  4737. Tools.Warn = Tools._WarnDisabled;
  4738. }
  4739. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4740. Tools.Error = Tools._ErrorEnabled;
  4741. }
  4742. else {
  4743. Tools.Error = Tools._ErrorDisabled;
  4744. }
  4745. },
  4746. enumerable: true,
  4747. configurable: true
  4748. });
  4749. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4750. get: function () {
  4751. return Tools._PerformanceNoneLogLevel;
  4752. },
  4753. enumerable: true,
  4754. configurable: true
  4755. });
  4756. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4757. get: function () {
  4758. return Tools._PerformanceUserMarkLogLevel;
  4759. },
  4760. enumerable: true,
  4761. configurable: true
  4762. });
  4763. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4764. get: function () {
  4765. return Tools._PerformanceConsoleLogLevel;
  4766. },
  4767. enumerable: true,
  4768. configurable: true
  4769. });
  4770. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4771. set: function (level) {
  4772. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4773. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4774. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4775. return;
  4776. }
  4777. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4778. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4779. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4780. return;
  4781. }
  4782. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4783. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4784. },
  4785. enumerable: true,
  4786. configurable: true
  4787. });
  4788. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4789. };
  4790. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4791. };
  4792. Tools._StartUserMark = function (counterName, condition) {
  4793. if (condition === void 0) { condition = true; }
  4794. if (!condition || !Tools._performance.mark) {
  4795. return;
  4796. }
  4797. Tools._performance.mark(counterName + "-Begin");
  4798. };
  4799. Tools._EndUserMark = function (counterName, condition) {
  4800. if (condition === void 0) { condition = true; }
  4801. if (!condition || !Tools._performance.mark) {
  4802. return;
  4803. }
  4804. Tools._performance.mark(counterName + "-End");
  4805. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4806. };
  4807. Tools._StartPerformanceConsole = function (counterName, condition) {
  4808. if (condition === void 0) { condition = true; }
  4809. if (!condition) {
  4810. return;
  4811. }
  4812. Tools._StartUserMark(counterName, condition);
  4813. if (console.time) {
  4814. console.time(counterName);
  4815. }
  4816. };
  4817. Tools._EndPerformanceConsole = function (counterName, condition) {
  4818. if (condition === void 0) { condition = true; }
  4819. if (!condition) {
  4820. return;
  4821. }
  4822. Tools._EndUserMark(counterName, condition);
  4823. if (console.time) {
  4824. console.timeEnd(counterName);
  4825. }
  4826. };
  4827. Object.defineProperty(Tools, "Now", {
  4828. get: function () {
  4829. if (window.performance && window.performance.now) {
  4830. return window.performance.now();
  4831. }
  4832. return new Date().getTime();
  4833. },
  4834. enumerable: true,
  4835. configurable: true
  4836. });
  4837. // Deprecated
  4838. Tools.GetFps = function () {
  4839. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4840. return 0;
  4841. };
  4842. Tools.BaseUrl = "";
  4843. // Logs
  4844. Tools._NoneLogLevel = 0;
  4845. Tools._MessageLogLevel = 1;
  4846. Tools._WarningLogLevel = 2;
  4847. Tools._ErrorLogLevel = 4;
  4848. Tools._LogCache = "";
  4849. Tools.Log = Tools._LogEnabled;
  4850. Tools.Warn = Tools._WarnEnabled;
  4851. Tools.Error = Tools._ErrorEnabled;
  4852. // Performances
  4853. Tools._PerformanceNoneLogLevel = 0;
  4854. Tools._PerformanceUserMarkLogLevel = 1;
  4855. Tools._PerformanceConsoleLogLevel = 2;
  4856. Tools._performance = window.performance;
  4857. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4858. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4859. return Tools;
  4860. })();
  4861. BABYLON.Tools = Tools;
  4862. /**
  4863. * An implementation of a loop for asynchronous functions.
  4864. */
  4865. var AsyncLoop = (function () {
  4866. /**
  4867. * Constroctor.
  4868. * @param iterations the number of iterations.
  4869. * @param _fn the function to run each iteration
  4870. * @param _successCallback the callback that will be called upon succesful execution
  4871. * @param offset starting offset.
  4872. */
  4873. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4874. if (offset === void 0) { offset = 0; }
  4875. this.iterations = iterations;
  4876. this._fn = _fn;
  4877. this._successCallback = _successCallback;
  4878. this.index = offset - 1;
  4879. this._done = false;
  4880. }
  4881. /**
  4882. * Execute the next iteration. Must be called after the last iteration was finished.
  4883. */
  4884. AsyncLoop.prototype.executeNext = function () {
  4885. if (!this._done) {
  4886. if (this.index + 1 < this.iterations) {
  4887. ++this.index;
  4888. this._fn(this);
  4889. }
  4890. else {
  4891. this.breakLoop();
  4892. }
  4893. }
  4894. };
  4895. /**
  4896. * Break the loop and run the success callback.
  4897. */
  4898. AsyncLoop.prototype.breakLoop = function () {
  4899. this._done = true;
  4900. this._successCallback();
  4901. };
  4902. /**
  4903. * Helper function
  4904. */
  4905. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4906. if (offset === void 0) { offset = 0; }
  4907. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4908. loop.executeNext();
  4909. return loop;
  4910. };
  4911. /**
  4912. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4913. * @param iterations total number of iterations
  4914. * @param syncedIterations number of synchronous iterations in each async iteration.
  4915. * @param fn the function to call each iteration.
  4916. * @param callback a success call back that will be called when iterating stops.
  4917. * @param breakFunction a break condition (optional)
  4918. * @param timeout timeout settings for the setTimeout function. default - 0.
  4919. * @constructor
  4920. */
  4921. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4922. if (timeout === void 0) { timeout = 0; }
  4923. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4924. if (breakFunction && breakFunction())
  4925. loop.breakLoop();
  4926. else {
  4927. setTimeout(function () {
  4928. for (var i = 0; i < syncedIterations; ++i) {
  4929. var iteration = (loop.index * syncedIterations) + i;
  4930. if (iteration >= iterations)
  4931. break;
  4932. fn(iteration);
  4933. if (breakFunction && breakFunction()) {
  4934. loop.breakLoop();
  4935. break;
  4936. }
  4937. }
  4938. loop.executeNext();
  4939. }, timeout);
  4940. }
  4941. }, callback);
  4942. };
  4943. return AsyncLoop;
  4944. })();
  4945. BABYLON.AsyncLoop = AsyncLoop;
  4946. })(BABYLON || (BABYLON = {}));
  4947. //# sourceMappingURL=babylon.tools.js.map
  4948. var BABYLON;
  4949. (function (BABYLON) {
  4950. var _DepthCullingState = (function () {
  4951. function _DepthCullingState() {
  4952. this._isDepthTestDirty = false;
  4953. this._isDepthMaskDirty = false;
  4954. this._isDepthFuncDirty = false;
  4955. this._isCullFaceDirty = false;
  4956. this._isCullDirty = false;
  4957. this._isZOffsetDirty = false;
  4958. }
  4959. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4960. get: function () {
  4961. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4962. },
  4963. enumerable: true,
  4964. configurable: true
  4965. });
  4966. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4967. get: function () {
  4968. return this._zOffset;
  4969. },
  4970. set: function (value) {
  4971. if (this._zOffset === value) {
  4972. return;
  4973. }
  4974. this._zOffset = value;
  4975. this._isZOffsetDirty = true;
  4976. },
  4977. enumerable: true,
  4978. configurable: true
  4979. });
  4980. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4981. get: function () {
  4982. return this._cullFace;
  4983. },
  4984. set: function (value) {
  4985. if (this._cullFace === value) {
  4986. return;
  4987. }
  4988. this._cullFace = value;
  4989. this._isCullFaceDirty = true;
  4990. },
  4991. enumerable: true,
  4992. configurable: true
  4993. });
  4994. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4995. get: function () {
  4996. return this._cull;
  4997. },
  4998. set: function (value) {
  4999. if (this._cull === value) {
  5000. return;
  5001. }
  5002. this._cull = value;
  5003. this._isCullDirty = true;
  5004. },
  5005. enumerable: true,
  5006. configurable: true
  5007. });
  5008. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5009. get: function () {
  5010. return this._depthFunc;
  5011. },
  5012. set: function (value) {
  5013. if (this._depthFunc === value) {
  5014. return;
  5015. }
  5016. this._depthFunc = value;
  5017. this._isDepthFuncDirty = true;
  5018. },
  5019. enumerable: true,
  5020. configurable: true
  5021. });
  5022. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5023. get: function () {
  5024. return this._depthMask;
  5025. },
  5026. set: function (value) {
  5027. if (this._depthMask === value) {
  5028. return;
  5029. }
  5030. this._depthMask = value;
  5031. this._isDepthMaskDirty = true;
  5032. },
  5033. enumerable: true,
  5034. configurable: true
  5035. });
  5036. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5037. get: function () {
  5038. return this._depthTest;
  5039. },
  5040. set: function (value) {
  5041. if (this._depthTest === value) {
  5042. return;
  5043. }
  5044. this._depthTest = value;
  5045. this._isDepthTestDirty = true;
  5046. },
  5047. enumerable: true,
  5048. configurable: true
  5049. });
  5050. _DepthCullingState.prototype.reset = function () {
  5051. this._depthMask = true;
  5052. this._depthTest = true;
  5053. this._depthFunc = null;
  5054. this._cull = null;
  5055. this._cullFace = null;
  5056. this._zOffset = 0;
  5057. this._isDepthTestDirty = true;
  5058. this._isDepthMaskDirty = true;
  5059. this._isDepthFuncDirty = false;
  5060. this._isCullFaceDirty = false;
  5061. this._isCullDirty = false;
  5062. this._isZOffsetDirty = false;
  5063. };
  5064. _DepthCullingState.prototype.apply = function (gl) {
  5065. if (!this.isDirty) {
  5066. return;
  5067. }
  5068. // Cull
  5069. if (this._isCullDirty) {
  5070. if (this.cull) {
  5071. gl.enable(gl.CULL_FACE);
  5072. }
  5073. else {
  5074. gl.disable(gl.CULL_FACE);
  5075. }
  5076. this._isCullDirty = false;
  5077. }
  5078. // Cull face
  5079. if (this._isCullFaceDirty) {
  5080. gl.cullFace(this.cullFace);
  5081. this._isCullFaceDirty = false;
  5082. }
  5083. // Depth mask
  5084. if (this._isDepthMaskDirty) {
  5085. gl.depthMask(this.depthMask);
  5086. this._isDepthMaskDirty = false;
  5087. }
  5088. // Depth test
  5089. if (this._isDepthTestDirty) {
  5090. if (this.depthTest) {
  5091. gl.enable(gl.DEPTH_TEST);
  5092. }
  5093. else {
  5094. gl.disable(gl.DEPTH_TEST);
  5095. }
  5096. this._isDepthTestDirty = false;
  5097. }
  5098. // Depth func
  5099. if (this._isDepthFuncDirty) {
  5100. gl.depthFunc(this.depthFunc);
  5101. this._isDepthFuncDirty = false;
  5102. }
  5103. // zOffset
  5104. if (this._isZOffsetDirty) {
  5105. if (this.zOffset) {
  5106. gl.enable(gl.POLYGON_OFFSET_FILL);
  5107. gl.polygonOffset(this.zOffset, 0);
  5108. }
  5109. else {
  5110. gl.disable(gl.POLYGON_OFFSET_FILL);
  5111. }
  5112. this._isZOffsetDirty = false;
  5113. }
  5114. };
  5115. return _DepthCullingState;
  5116. })();
  5117. BABYLON._DepthCullingState = _DepthCullingState;
  5118. var _AlphaState = (function () {
  5119. function _AlphaState() {
  5120. this._isAlphaBlendDirty = false;
  5121. this._isBlendFunctionParametersDirty = false;
  5122. this._alphaBlend = false;
  5123. this._blendFunctionParameters = new Array(4);
  5124. }
  5125. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5126. get: function () {
  5127. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5128. },
  5129. enumerable: true,
  5130. configurable: true
  5131. });
  5132. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5133. get: function () {
  5134. return this._alphaBlend;
  5135. },
  5136. set: function (value) {
  5137. if (this._alphaBlend === value) {
  5138. return;
  5139. }
  5140. this._alphaBlend = value;
  5141. this._isAlphaBlendDirty = true;
  5142. },
  5143. enumerable: true,
  5144. configurable: true
  5145. });
  5146. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5147. if (this._blendFunctionParameters[0] === value0 &&
  5148. this._blendFunctionParameters[1] === value1 &&
  5149. this._blendFunctionParameters[2] === value2 &&
  5150. this._blendFunctionParameters[3] === value3) {
  5151. return;
  5152. }
  5153. this._blendFunctionParameters[0] = value0;
  5154. this._blendFunctionParameters[1] = value1;
  5155. this._blendFunctionParameters[2] = value2;
  5156. this._blendFunctionParameters[3] = value3;
  5157. this._isBlendFunctionParametersDirty = true;
  5158. };
  5159. _AlphaState.prototype.reset = function () {
  5160. this._alphaBlend = false;
  5161. this._blendFunctionParameters[0] = null;
  5162. this._blendFunctionParameters[1] = null;
  5163. this._blendFunctionParameters[2] = null;
  5164. this._blendFunctionParameters[3] = null;
  5165. this._isAlphaBlendDirty = true;
  5166. this._isBlendFunctionParametersDirty = false;
  5167. };
  5168. _AlphaState.prototype.apply = function (gl) {
  5169. if (!this.isDirty) {
  5170. return;
  5171. }
  5172. // Alpha blend
  5173. if (this._isAlphaBlendDirty) {
  5174. if (this._alphaBlend) {
  5175. gl.enable(gl.BLEND);
  5176. }
  5177. else {
  5178. gl.disable(gl.BLEND);
  5179. }
  5180. this._isAlphaBlendDirty = false;
  5181. }
  5182. // Alpha function
  5183. if (this._isBlendFunctionParametersDirty) {
  5184. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5185. this._isBlendFunctionParametersDirty = false;
  5186. }
  5187. };
  5188. return _AlphaState;
  5189. })();
  5190. BABYLON._AlphaState = _AlphaState;
  5191. var compileShader = function (gl, source, type, defines) {
  5192. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5193. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5194. gl.compileShader(shader);
  5195. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5196. throw new Error(gl.getShaderInfoLog(shader));
  5197. }
  5198. return shader;
  5199. };
  5200. var getWebGLTextureType = function (gl, type) {
  5201. var textureType = gl.UNSIGNED_BYTE;
  5202. if (type === Engine.TEXTURETYPE_FLOAT)
  5203. textureType = gl.FLOAT;
  5204. return textureType;
  5205. };
  5206. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5207. var magFilter = gl.NEAREST;
  5208. var minFilter = gl.NEAREST;
  5209. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5210. magFilter = gl.LINEAR;
  5211. if (generateMipMaps) {
  5212. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5213. }
  5214. else {
  5215. minFilter = gl.LINEAR;
  5216. }
  5217. }
  5218. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5219. magFilter = gl.LINEAR;
  5220. if (generateMipMaps) {
  5221. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5222. }
  5223. else {
  5224. minFilter = gl.LINEAR;
  5225. }
  5226. }
  5227. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5228. magFilter = gl.NEAREST;
  5229. if (generateMipMaps) {
  5230. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5231. }
  5232. else {
  5233. minFilter = gl.NEAREST;
  5234. }
  5235. }
  5236. return {
  5237. min: minFilter,
  5238. mag: magFilter
  5239. };
  5240. };
  5241. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5242. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5243. var engine = scene.getEngine();
  5244. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5245. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5246. gl.bindTexture(gl.TEXTURE_2D, texture);
  5247. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5248. texture._baseWidth = width;
  5249. texture._baseHeight = height;
  5250. texture._width = potWidth;
  5251. texture._height = potHeight;
  5252. texture.isReady = true;
  5253. processFunction(potWidth, potHeight);
  5254. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5255. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5256. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5257. if (!noMipmap && !isCompressed) {
  5258. gl.generateMipmap(gl.TEXTURE_2D);
  5259. }
  5260. gl.bindTexture(gl.TEXTURE_2D, null);
  5261. engine._activeTexturesCache = [];
  5262. scene._removePendingData(texture);
  5263. };
  5264. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5265. var onload = function () {
  5266. loadedImages[index] = img;
  5267. loadedImages._internalCount++;
  5268. scene._removePendingData(img);
  5269. if (loadedImages._internalCount === 6) {
  5270. onfinish(loadedImages);
  5271. }
  5272. };
  5273. var onerror = function () {
  5274. scene._removePendingData(img);
  5275. };
  5276. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5277. scene._addPendingData(img);
  5278. };
  5279. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5280. var loadedImages = [];
  5281. loadedImages._internalCount = 0;
  5282. for (var index = 0; index < 6; index++) {
  5283. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5284. }
  5285. };
  5286. var EngineCapabilities = (function () {
  5287. function EngineCapabilities() {
  5288. }
  5289. return EngineCapabilities;
  5290. })();
  5291. BABYLON.EngineCapabilities = EngineCapabilities;
  5292. /**
  5293. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5294. */
  5295. var Engine = (function () {
  5296. /**
  5297. * @constructor
  5298. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5299. * @param {boolean} [antialias] - enable antialias
  5300. * @param options - further options to be sent to the getContext function
  5301. */
  5302. function Engine(canvas, antialias, options) {
  5303. var _this = this;
  5304. // Public members
  5305. this.isFullscreen = false;
  5306. this.isPointerLock = false;
  5307. this.cullBackFaces = true;
  5308. this.renderEvenInBackground = true;
  5309. this.scenes = new Array();
  5310. this._windowIsBackground = false;
  5311. this._loadingDivBackgroundColor = "black";
  5312. this._drawCalls = 0;
  5313. this._renderingQueueLaunched = false;
  5314. this._activeRenderLoops = [];
  5315. // FPS
  5316. this.fpsRange = 60;
  5317. this.previousFramesDuration = [];
  5318. this.fps = 60;
  5319. this.deltaTime = 0;
  5320. // States
  5321. this._depthCullingState = new _DepthCullingState();
  5322. this._alphaState = new _AlphaState();
  5323. this._alphaMode = Engine.ALPHA_DISABLE;
  5324. // Cache
  5325. this._loadedTexturesCache = new Array();
  5326. this._activeTexturesCache = new Array();
  5327. this._compiledEffects = {};
  5328. this._uintIndicesCurrentlySet = false;
  5329. this._renderingCanvas = canvas;
  5330. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5331. options = options || {};
  5332. options.antialias = antialias;
  5333. // GL
  5334. try {
  5335. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  5336. }
  5337. catch (e) {
  5338. throw new Error("WebGL not supported");
  5339. }
  5340. if (!this._gl) {
  5341. throw new Error("WebGL not supported");
  5342. }
  5343. this._onBlur = function () {
  5344. _this._windowIsBackground = true;
  5345. };
  5346. this._onFocus = function () {
  5347. _this._windowIsBackground = false;
  5348. };
  5349. window.addEventListener("blur", this._onBlur);
  5350. window.addEventListener("focus", this._onFocus);
  5351. // Viewport
  5352. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5353. this.resize();
  5354. // Caps
  5355. this._caps = new EngineCapabilities();
  5356. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5357. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5358. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5359. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5360. // Infos
  5361. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5362. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5363. if (rendererInfo != null) {
  5364. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5365. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5366. }
  5367. if (!this._glVendor) {
  5368. this._glVendor = "Unknown vendor";
  5369. }
  5370. if (!this._glRenderer) {
  5371. this._glRenderer = "Unknown renderer";
  5372. }
  5373. // Extensions
  5374. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5375. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5376. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5377. 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');
  5378. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5379. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5380. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5381. this._caps.highPrecisionShaderSupported = true;
  5382. if (this._gl.getShaderPrecisionFormat) {
  5383. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5384. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5385. }
  5386. // Depth buffer
  5387. this.setDepthBuffer(true);
  5388. this.setDepthFunctionToLessOrEqual();
  5389. this.setDepthWrite(true);
  5390. // Fullscreen
  5391. this._onFullscreenChange = function () {
  5392. if (document.fullscreen !== undefined) {
  5393. _this.isFullscreen = document.fullscreen;
  5394. }
  5395. else if (document.mozFullScreen !== undefined) {
  5396. _this.isFullscreen = document.mozFullScreen;
  5397. }
  5398. else if (document.webkitIsFullScreen !== undefined) {
  5399. _this.isFullscreen = document.webkitIsFullScreen;
  5400. }
  5401. else if (document.msIsFullScreen !== undefined) {
  5402. _this.isFullscreen = document.msIsFullScreen;
  5403. }
  5404. // Pointer lock
  5405. if (_this.isFullscreen && _this._pointerLockRequested) {
  5406. canvas.requestPointerLock = canvas.requestPointerLock ||
  5407. canvas.msRequestPointerLock ||
  5408. canvas.mozRequestPointerLock ||
  5409. canvas.webkitRequestPointerLock;
  5410. if (canvas.requestPointerLock) {
  5411. canvas.requestPointerLock();
  5412. }
  5413. }
  5414. };
  5415. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5416. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5417. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5418. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5419. // Pointer lock
  5420. this._onPointerLockChange = function () {
  5421. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5422. document.webkitPointerLockElement === canvas ||
  5423. document.msPointerLockElement === canvas ||
  5424. document.pointerLockElement === canvas);
  5425. };
  5426. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5427. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5428. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5429. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5430. if (!Engine.audioEngine) {
  5431. Engine.audioEngine = new BABYLON.AudioEngine();
  5432. }
  5433. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5434. }
  5435. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5436. get: function () {
  5437. return Engine._ALPHA_DISABLE;
  5438. },
  5439. enumerable: true,
  5440. configurable: true
  5441. });
  5442. Object.defineProperty(Engine, "ALPHA_ADD", {
  5443. get: function () {
  5444. return Engine._ALPHA_ADD;
  5445. },
  5446. enumerable: true,
  5447. configurable: true
  5448. });
  5449. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5450. get: function () {
  5451. return Engine._ALPHA_COMBINE;
  5452. },
  5453. enumerable: true,
  5454. configurable: true
  5455. });
  5456. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5457. get: function () {
  5458. return Engine._DELAYLOADSTATE_NONE;
  5459. },
  5460. enumerable: true,
  5461. configurable: true
  5462. });
  5463. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5464. get: function () {
  5465. return Engine._DELAYLOADSTATE_LOADED;
  5466. },
  5467. enumerable: true,
  5468. configurable: true
  5469. });
  5470. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5471. get: function () {
  5472. return Engine._DELAYLOADSTATE_LOADING;
  5473. },
  5474. enumerable: true,
  5475. configurable: true
  5476. });
  5477. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5478. get: function () {
  5479. return Engine._DELAYLOADSTATE_NOTLOADED;
  5480. },
  5481. enumerable: true,
  5482. configurable: true
  5483. });
  5484. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5485. get: function () {
  5486. return Engine._TEXTUREFORMAT_ALPHA;
  5487. },
  5488. enumerable: true,
  5489. configurable: true
  5490. });
  5491. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5492. get: function () {
  5493. return Engine._TEXTUREFORMAT_LUMINANCE;
  5494. },
  5495. enumerable: true,
  5496. configurable: true
  5497. });
  5498. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5499. get: function () {
  5500. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5501. },
  5502. enumerable: true,
  5503. configurable: true
  5504. });
  5505. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5506. get: function () {
  5507. return Engine._TEXTUREFORMAT_RGB;
  5508. },
  5509. enumerable: true,
  5510. configurable: true
  5511. });
  5512. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5513. get: function () {
  5514. return Engine._TEXTUREFORMAT_RGBA;
  5515. },
  5516. enumerable: true,
  5517. configurable: true
  5518. });
  5519. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5520. get: function () {
  5521. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5522. },
  5523. enumerable: true,
  5524. configurable: true
  5525. });
  5526. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5527. get: function () {
  5528. return Engine._TEXTURETYPE_FLOAT;
  5529. },
  5530. enumerable: true,
  5531. configurable: true
  5532. });
  5533. Object.defineProperty(Engine, "Version", {
  5534. get: function () {
  5535. return "2.1.0 beta";
  5536. },
  5537. enumerable: true,
  5538. configurable: true
  5539. });
  5540. Engine.prototype._prepareWorkingCanvas = function () {
  5541. if (this._workingCanvas) {
  5542. return;
  5543. }
  5544. this._workingCanvas = document.createElement("canvas");
  5545. this._workingContext = this._workingCanvas.getContext("2d");
  5546. };
  5547. Engine.prototype.getGlInfo = function () {
  5548. return {
  5549. vendor: this._glVendor,
  5550. renderer: this._glRenderer,
  5551. version: this._glVersion
  5552. };
  5553. };
  5554. Engine.prototype.getAspectRatio = function (camera) {
  5555. var viewport = camera.viewport;
  5556. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5557. };
  5558. Engine.prototype.getRenderWidth = function () {
  5559. if (this._currentRenderTarget) {
  5560. return this._currentRenderTarget._width;
  5561. }
  5562. return this._renderingCanvas.width;
  5563. };
  5564. Engine.prototype.getRenderHeight = function () {
  5565. if (this._currentRenderTarget) {
  5566. return this._currentRenderTarget._height;
  5567. }
  5568. return this._renderingCanvas.height;
  5569. };
  5570. Engine.prototype.getRenderingCanvas = function () {
  5571. return this._renderingCanvas;
  5572. };
  5573. Engine.prototype.getRenderingCanvasClientRect = function () {
  5574. return this._renderingCanvas.getBoundingClientRect();
  5575. };
  5576. Engine.prototype.setHardwareScalingLevel = function (level) {
  5577. this._hardwareScalingLevel = level;
  5578. this.resize();
  5579. };
  5580. Engine.prototype.getHardwareScalingLevel = function () {
  5581. return this._hardwareScalingLevel;
  5582. };
  5583. Engine.prototype.getLoadedTexturesCache = function () {
  5584. return this._loadedTexturesCache;
  5585. };
  5586. Engine.prototype.getCaps = function () {
  5587. return this._caps;
  5588. };
  5589. Object.defineProperty(Engine.prototype, "drawCalls", {
  5590. get: function () {
  5591. return this._drawCalls;
  5592. },
  5593. enumerable: true,
  5594. configurable: true
  5595. });
  5596. // Methods
  5597. Engine.prototype.resetDrawCalls = function () {
  5598. this._drawCalls = 0;
  5599. };
  5600. Engine.prototype.setDepthFunctionToGreater = function () {
  5601. this._depthCullingState.depthFunc = this._gl.GREATER;
  5602. };
  5603. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5604. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5605. };
  5606. Engine.prototype.setDepthFunctionToLess = function () {
  5607. this._depthCullingState.depthFunc = this._gl.LESS;
  5608. };
  5609. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5610. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5611. };
  5612. /**
  5613. * stop executing a render loop function and remove it from the execution array
  5614. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5615. */
  5616. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5617. if (!renderFunction) {
  5618. this._activeRenderLoops = [];
  5619. return;
  5620. }
  5621. var index = this._activeRenderLoops.indexOf(renderFunction);
  5622. if (index >= 0) {
  5623. this._activeRenderLoops.splice(index, 1);
  5624. }
  5625. };
  5626. Engine.prototype._renderLoop = function () {
  5627. var _this = this;
  5628. var shouldRender = true;
  5629. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5630. shouldRender = false;
  5631. }
  5632. if (shouldRender) {
  5633. // Start new frame
  5634. this.beginFrame();
  5635. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5636. var renderFunction = this._activeRenderLoops[index];
  5637. renderFunction();
  5638. }
  5639. // Present
  5640. this.endFrame();
  5641. }
  5642. if (this._activeRenderLoops.length > 0) {
  5643. // Register new frame
  5644. BABYLON.Tools.QueueNewFrame(function () {
  5645. _this._renderLoop();
  5646. });
  5647. }
  5648. else {
  5649. this._renderingQueueLaunched = false;
  5650. }
  5651. };
  5652. /**
  5653. * Register and execute a render loop. The engine can have more than one render function.
  5654. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5655. * @example
  5656. * engine.runRenderLoop(function () {
  5657. * scene.render()
  5658. * })
  5659. */
  5660. Engine.prototype.runRenderLoop = function (renderFunction) {
  5661. var _this = this;
  5662. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5663. return;
  5664. }
  5665. this._activeRenderLoops.push(renderFunction);
  5666. if (!this._renderingQueueLaunched) {
  5667. this._renderingQueueLaunched = true;
  5668. BABYLON.Tools.QueueNewFrame(function () {
  5669. _this._renderLoop();
  5670. });
  5671. }
  5672. };
  5673. /**
  5674. * Toggle full screen mode.
  5675. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5676. */
  5677. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5678. if (this.isFullscreen) {
  5679. BABYLON.Tools.ExitFullscreen();
  5680. }
  5681. else {
  5682. this._pointerLockRequested = requestPointerLock;
  5683. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5684. }
  5685. };
  5686. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5687. this.applyStates();
  5688. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5689. if (this._depthCullingState.depthMask) {
  5690. this._gl.clearDepth(1.0);
  5691. }
  5692. var mode = 0;
  5693. if (backBuffer)
  5694. mode |= this._gl.COLOR_BUFFER_BIT;
  5695. if (depthStencil && this._depthCullingState.depthMask)
  5696. mode |= this._gl.DEPTH_BUFFER_BIT;
  5697. this._gl.clear(mode);
  5698. };
  5699. /**
  5700. * Set the WebGL's viewport
  5701. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5702. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5703. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5704. */
  5705. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5706. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5707. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5708. var x = viewport.x || 0;
  5709. var y = viewport.y || 0;
  5710. this._cachedViewport = viewport;
  5711. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5712. };
  5713. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5714. this._cachedViewport = null;
  5715. this._gl.viewport(x, y, width, height);
  5716. };
  5717. Engine.prototype.beginFrame = function () {
  5718. this._measureFps();
  5719. };
  5720. Engine.prototype.endFrame = function () {
  5721. //this.flushFramebuffer();
  5722. };
  5723. /**
  5724. * resize the view according to the canvas' size.
  5725. * @example
  5726. * window.addEventListener("resize", function () {
  5727. * engine.resize();
  5728. * });
  5729. */
  5730. Engine.prototype.resize = function () {
  5731. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5732. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5733. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5734. };
  5735. /**
  5736. * force a specific size of the canvas
  5737. * @param {number} width - the new canvas' width
  5738. * @param {number} height - the new canvas' height
  5739. */
  5740. Engine.prototype.setSize = function (width, height) {
  5741. this._renderingCanvas.width = width;
  5742. this._renderingCanvas.height = height;
  5743. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5744. for (var index = 0; index < this.scenes.length; index++) {
  5745. var scene = this.scenes[index];
  5746. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5747. var cam = scene.cameras[camIndex];
  5748. cam._currentRenderId = 0;
  5749. }
  5750. }
  5751. };
  5752. Engine.prototype.bindFramebuffer = function (texture) {
  5753. this._currentRenderTarget = texture;
  5754. var gl = this._gl;
  5755. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5756. this._gl.viewport(0, 0, texture._width, texture._height);
  5757. this.wipeCaches();
  5758. };
  5759. Engine.prototype.unBindFramebuffer = function (texture) {
  5760. this._currentRenderTarget = null;
  5761. if (texture.generateMipMaps) {
  5762. var gl = this._gl;
  5763. gl.bindTexture(gl.TEXTURE_2D, texture);
  5764. gl.generateMipmap(gl.TEXTURE_2D);
  5765. gl.bindTexture(gl.TEXTURE_2D, null);
  5766. }
  5767. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5768. };
  5769. Engine.prototype.flushFramebuffer = function () {
  5770. this._gl.flush();
  5771. };
  5772. Engine.prototype.restoreDefaultFramebuffer = function () {
  5773. this._currentRenderTarget = null;
  5774. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5775. this.setViewport(this._cachedViewport);
  5776. this.wipeCaches();
  5777. };
  5778. // VBOs
  5779. Engine.prototype._resetVertexBufferBinding = function () {
  5780. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5781. this._cachedVertexBuffers = null;
  5782. };
  5783. Engine.prototype.createVertexBuffer = function (vertices) {
  5784. var vbo = this._gl.createBuffer();
  5785. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5786. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5787. this._resetVertexBufferBinding();
  5788. vbo.references = 1;
  5789. return vbo;
  5790. };
  5791. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5792. var vbo = this._gl.createBuffer();
  5793. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5794. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5795. this._resetVertexBufferBinding();
  5796. vbo.references = 1;
  5797. return vbo;
  5798. };
  5799. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5800. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5801. if (offset === undefined) {
  5802. offset = 0;
  5803. }
  5804. if (vertices instanceof Float32Array) {
  5805. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5806. }
  5807. else {
  5808. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5809. }
  5810. this._resetVertexBufferBinding();
  5811. };
  5812. Engine.prototype._resetIndexBufferBinding = function () {
  5813. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5814. this._cachedIndexBuffer = null;
  5815. };
  5816. Engine.prototype.createIndexBuffer = function (indices) {
  5817. var vbo = this._gl.createBuffer();
  5818. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5819. // Check for 32 bits indices
  5820. var arrayBuffer;
  5821. var need32Bits = false;
  5822. if (this._caps.uintIndices) {
  5823. for (var index = 0; index < indices.length; index++) {
  5824. if (indices[index] > 65535) {
  5825. need32Bits = true;
  5826. break;
  5827. }
  5828. }
  5829. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5830. }
  5831. else {
  5832. arrayBuffer = new Uint16Array(indices);
  5833. }
  5834. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5835. this._resetIndexBufferBinding();
  5836. vbo.references = 1;
  5837. vbo.is32Bits = need32Bits;
  5838. return vbo;
  5839. };
  5840. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5841. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5842. this._cachedVertexBuffers = vertexBuffer;
  5843. this._cachedEffectForVertexBuffers = effect;
  5844. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5845. var offset = 0;
  5846. for (var index = 0; index < vertexDeclaration.length; index++) {
  5847. var order = effect.getAttributeLocation(index);
  5848. if (order >= 0) {
  5849. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5850. }
  5851. offset += vertexDeclaration[index] * 4;
  5852. }
  5853. }
  5854. if (this._cachedIndexBuffer !== indexBuffer) {
  5855. this._cachedIndexBuffer = indexBuffer;
  5856. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5857. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5858. }
  5859. };
  5860. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5861. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5862. this._cachedVertexBuffers = vertexBuffers;
  5863. this._cachedEffectForVertexBuffers = effect;
  5864. var attributes = effect.getAttributesNames();
  5865. for (var index = 0; index < attributes.length; index++) {
  5866. var order = effect.getAttributeLocation(index);
  5867. if (order >= 0) {
  5868. var vertexBuffer = vertexBuffers[attributes[index]];
  5869. if (!vertexBuffer) {
  5870. continue;
  5871. }
  5872. var stride = vertexBuffer.getStrideSize();
  5873. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5874. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5875. }
  5876. }
  5877. }
  5878. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5879. this._cachedIndexBuffer = indexBuffer;
  5880. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5881. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5882. }
  5883. };
  5884. Engine.prototype._releaseBuffer = function (buffer) {
  5885. buffer.references--;
  5886. if (buffer.references === 0) {
  5887. this._gl.deleteBuffer(buffer);
  5888. return true;
  5889. }
  5890. return false;
  5891. };
  5892. Engine.prototype.createInstancesBuffer = function (capacity) {
  5893. var buffer = this._gl.createBuffer();
  5894. buffer.capacity = capacity;
  5895. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5896. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5897. return buffer;
  5898. };
  5899. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5900. this._gl.deleteBuffer(buffer);
  5901. };
  5902. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5903. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5904. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5905. for (var index = 0; index < 4; index++) {
  5906. var offsetLocation = offsetLocations[index];
  5907. this._gl.enableVertexAttribArray(offsetLocation);
  5908. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5909. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5910. }
  5911. };
  5912. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5913. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5914. for (var index = 0; index < 4; index++) {
  5915. var offsetLocation = offsetLocations[index];
  5916. this._gl.disableVertexAttribArray(offsetLocation);
  5917. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5918. }
  5919. };
  5920. Engine.prototype.applyStates = function () {
  5921. this._depthCullingState.apply(this._gl);
  5922. this._alphaState.apply(this._gl);
  5923. };
  5924. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5925. // Apply states
  5926. this.applyStates();
  5927. this._drawCalls++;
  5928. // Render
  5929. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5930. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5931. if (instancesCount) {
  5932. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5933. return;
  5934. }
  5935. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5936. };
  5937. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5938. // Apply states
  5939. this.applyStates();
  5940. this._drawCalls++;
  5941. if (instancesCount) {
  5942. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5943. return;
  5944. }
  5945. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5946. };
  5947. // Shaders
  5948. Engine.prototype._releaseEffect = function (effect) {
  5949. if (this._compiledEffects[effect._key]) {
  5950. delete this._compiledEffects[effect._key];
  5951. if (effect.getProgram()) {
  5952. this._gl.deleteProgram(effect.getProgram());
  5953. }
  5954. }
  5955. };
  5956. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5957. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5958. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5959. var name = vertex + "+" + fragment + "@" + defines;
  5960. if (this._compiledEffects[name]) {
  5961. return this._compiledEffects[name];
  5962. }
  5963. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5964. effect._key = name;
  5965. this._compiledEffects[name] = effect;
  5966. return effect;
  5967. };
  5968. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5969. if (uniformsNames === void 0) { uniformsNames = []; }
  5970. if (samplers === void 0) { samplers = []; }
  5971. if (defines === void 0) { defines = ""; }
  5972. return this.createEffect({
  5973. vertex: "particles",
  5974. fragmentElement: fragmentName
  5975. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5976. };
  5977. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5978. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5979. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5980. var shaderProgram = this._gl.createProgram();
  5981. this._gl.attachShader(shaderProgram, vertexShader);
  5982. this._gl.attachShader(shaderProgram, fragmentShader);
  5983. this._gl.linkProgram(shaderProgram);
  5984. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5985. if (!linked) {
  5986. var error = this._gl.getProgramInfoLog(shaderProgram);
  5987. if (error) {
  5988. throw new Error(error);
  5989. }
  5990. }
  5991. this._gl.deleteShader(vertexShader);
  5992. this._gl.deleteShader(fragmentShader);
  5993. return shaderProgram;
  5994. };
  5995. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5996. var results = [];
  5997. for (var index = 0; index < uniformsNames.length; index++) {
  5998. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5999. }
  6000. return results;
  6001. };
  6002. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6003. var results = [];
  6004. for (var index = 0; index < attributesNames.length; index++) {
  6005. try {
  6006. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6007. }
  6008. catch (e) {
  6009. results.push(-1);
  6010. }
  6011. }
  6012. return results;
  6013. };
  6014. Engine.prototype.enableEffect = function (effect) {
  6015. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6016. if (effect && effect.onBind) {
  6017. effect.onBind(effect);
  6018. }
  6019. return;
  6020. }
  6021. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6022. // Use program
  6023. this._gl.useProgram(effect.getProgram());
  6024. for (var i in this._vertexAttribArrays) {
  6025. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6026. continue;
  6027. }
  6028. this._vertexAttribArrays[i] = false;
  6029. this._gl.disableVertexAttribArray(i);
  6030. }
  6031. var attributesCount = effect.getAttributesCount();
  6032. for (var index = 0; index < attributesCount; index++) {
  6033. // Attributes
  6034. var order = effect.getAttributeLocation(index);
  6035. if (order >= 0) {
  6036. this._vertexAttribArrays[order] = true;
  6037. this._gl.enableVertexAttribArray(order);
  6038. }
  6039. }
  6040. this._currentEffect = effect;
  6041. if (effect.onBind) {
  6042. effect.onBind(effect);
  6043. }
  6044. };
  6045. Engine.prototype.setArray = function (uniform, array) {
  6046. if (!uniform)
  6047. return;
  6048. this._gl.uniform1fv(uniform, array);
  6049. };
  6050. Engine.prototype.setArray2 = function (uniform, array) {
  6051. if (!uniform || array.length % 2 !== 0)
  6052. return;
  6053. this._gl.uniform2fv(uniform, array);
  6054. };
  6055. Engine.prototype.setArray3 = function (uniform, array) {
  6056. if (!uniform || array.length % 3 !== 0)
  6057. return;
  6058. this._gl.uniform3fv(uniform, array);
  6059. };
  6060. Engine.prototype.setArray4 = function (uniform, array) {
  6061. if (!uniform || array.length % 4 !== 0)
  6062. return;
  6063. this._gl.uniform4fv(uniform, array);
  6064. };
  6065. Engine.prototype.setMatrices = function (uniform, matrices) {
  6066. if (!uniform)
  6067. return;
  6068. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6069. };
  6070. Engine.prototype.setMatrix = function (uniform, matrix) {
  6071. if (!uniform)
  6072. return;
  6073. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6074. };
  6075. Engine.prototype.setFloat = function (uniform, value) {
  6076. if (!uniform)
  6077. return;
  6078. this._gl.uniform1f(uniform, value);
  6079. };
  6080. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6081. if (!uniform)
  6082. return;
  6083. this._gl.uniform2f(uniform, x, y);
  6084. };
  6085. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6086. if (!uniform)
  6087. return;
  6088. this._gl.uniform3f(uniform, x, y, z);
  6089. };
  6090. Engine.prototype.setBool = function (uniform, bool) {
  6091. if (!uniform)
  6092. return;
  6093. this._gl.uniform1i(uniform, bool);
  6094. };
  6095. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6096. if (!uniform)
  6097. return;
  6098. this._gl.uniform4f(uniform, x, y, z, w);
  6099. };
  6100. Engine.prototype.setColor3 = function (uniform, color3) {
  6101. if (!uniform)
  6102. return;
  6103. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6104. };
  6105. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6106. if (!uniform)
  6107. return;
  6108. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6109. };
  6110. // States
  6111. Engine.prototype.setState = function (culling, zOffset, force) {
  6112. if (zOffset === void 0) { zOffset = 0; }
  6113. // Culling
  6114. if (this._depthCullingState.cull !== culling || force) {
  6115. if (culling) {
  6116. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6117. this._depthCullingState.cull = true;
  6118. }
  6119. else {
  6120. this._depthCullingState.cull = false;
  6121. }
  6122. }
  6123. // Z offset
  6124. this._depthCullingState.zOffset = zOffset;
  6125. };
  6126. Engine.prototype.setDepthBuffer = function (enable) {
  6127. this._depthCullingState.depthTest = enable;
  6128. };
  6129. Engine.prototype.getDepthWrite = function () {
  6130. return this._depthCullingState.depthMask;
  6131. };
  6132. Engine.prototype.setDepthWrite = function (enable) {
  6133. this._depthCullingState.depthMask = enable;
  6134. };
  6135. Engine.prototype.setColorWrite = function (enable) {
  6136. this._gl.colorMask(enable, enable, enable, enable);
  6137. };
  6138. Engine.prototype.setAlphaMode = function (mode) {
  6139. switch (mode) {
  6140. case Engine.ALPHA_DISABLE:
  6141. this.setDepthWrite(true);
  6142. this._alphaState.alphaBlend = false;
  6143. break;
  6144. case Engine.ALPHA_COMBINE:
  6145. this.setDepthWrite(false);
  6146. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6147. this._alphaState.alphaBlend = true;
  6148. break;
  6149. case Engine.ALPHA_ADD:
  6150. this.setDepthWrite(false);
  6151. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6152. this._alphaState.alphaBlend = true;
  6153. break;
  6154. }
  6155. this._alphaMode = mode;
  6156. };
  6157. Engine.prototype.getAlphaMode = function () {
  6158. return this._alphaMode;
  6159. };
  6160. Engine.prototype.setAlphaTesting = function (enable) {
  6161. this._alphaTest = enable;
  6162. };
  6163. Engine.prototype.getAlphaTesting = function () {
  6164. return this._alphaTest;
  6165. };
  6166. // Textures
  6167. Engine.prototype.wipeCaches = function () {
  6168. this._activeTexturesCache = [];
  6169. this._currentEffect = null;
  6170. this._depthCullingState.reset();
  6171. this._alphaState.reset();
  6172. this._cachedVertexBuffers = null;
  6173. this._cachedIndexBuffer = null;
  6174. this._cachedEffectForVertexBuffers = null;
  6175. };
  6176. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6177. var gl = this._gl;
  6178. gl.bindTexture(gl.TEXTURE_2D, texture);
  6179. var magFilter = gl.NEAREST;
  6180. var minFilter = gl.NEAREST;
  6181. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6182. magFilter = gl.LINEAR;
  6183. minFilter = gl.LINEAR;
  6184. }
  6185. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6186. magFilter = gl.LINEAR;
  6187. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6188. }
  6189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6191. gl.bindTexture(gl.TEXTURE_2D, null);
  6192. texture.samplingMode = samplingMode;
  6193. };
  6194. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6195. var _this = this;
  6196. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6197. if (onLoad === void 0) { onLoad = null; }
  6198. if (onError === void 0) { onError = null; }
  6199. if (buffer === void 0) { buffer = null; }
  6200. var texture = this._gl.createTexture();
  6201. var extension;
  6202. var fromData = false;
  6203. if (url.substr(0, 5) === "data:") {
  6204. fromData = true;
  6205. }
  6206. if (!fromData)
  6207. extension = url.substr(url.length - 4, 4).toLowerCase();
  6208. else {
  6209. var oldUrl = url;
  6210. fromData = oldUrl.split(':');
  6211. url = oldUrl;
  6212. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6213. }
  6214. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6215. var isTGA = (extension === ".tga");
  6216. scene._addPendingData(texture);
  6217. texture.url = url;
  6218. texture.noMipmap = noMipmap;
  6219. texture.references = 1;
  6220. texture.samplingMode = samplingMode;
  6221. this._loadedTexturesCache.push(texture);
  6222. var onerror = function () {
  6223. scene._removePendingData(texture);
  6224. if (onError) {
  6225. onError();
  6226. }
  6227. };
  6228. if (isTGA) {
  6229. var callback = function (arrayBuffer) {
  6230. var data = new Uint8Array(arrayBuffer);
  6231. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6232. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6233. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6234. if (onLoad) {
  6235. onLoad();
  6236. }
  6237. }, samplingMode);
  6238. };
  6239. if (!(fromData instanceof Array))
  6240. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6241. callback(arrayBuffer);
  6242. }, onerror, scene.database, true);
  6243. else
  6244. callback(buffer);
  6245. }
  6246. else if (isDDS) {
  6247. callback = function (data) {
  6248. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6249. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6250. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6251. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6252. if (onLoad) {
  6253. onLoad();
  6254. }
  6255. }, samplingMode);
  6256. };
  6257. if (!(fromData instanceof Array))
  6258. BABYLON.Tools.LoadFile(url, function (data) {
  6259. callback(data);
  6260. }, onerror, scene.database, true);
  6261. else
  6262. callback(buffer);
  6263. }
  6264. else {
  6265. var onload = function (img) {
  6266. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6267. var isPot = (img.width === potWidth && img.height === potHeight);
  6268. if (!isPot) {
  6269. _this._prepareWorkingCanvas();
  6270. _this._workingCanvas.width = potWidth;
  6271. _this._workingCanvas.height = potHeight;
  6272. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6273. _this._workingContext.imageSmoothingEnabled = false;
  6274. _this._workingContext.mozImageSmoothingEnabled = false;
  6275. _this._workingContext.oImageSmoothingEnabled = false;
  6276. _this._workingContext.webkitImageSmoothingEnabled = false;
  6277. _this._workingContext.msImageSmoothingEnabled = false;
  6278. }
  6279. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6280. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6281. _this._workingContext.imageSmoothingEnabled = true;
  6282. _this._workingContext.mozImageSmoothingEnabled = true;
  6283. _this._workingContext.oImageSmoothingEnabled = true;
  6284. _this._workingContext.webkitImageSmoothingEnabled = true;
  6285. _this._workingContext.msImageSmoothingEnabled = true;
  6286. }
  6287. }
  6288. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6289. if (onLoad) {
  6290. onLoad();
  6291. }
  6292. }, samplingMode);
  6293. };
  6294. if (!(fromData instanceof Array))
  6295. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6296. else
  6297. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6298. }
  6299. return texture;
  6300. };
  6301. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6302. var texture = this._gl.createTexture();
  6303. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6304. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6305. // Format
  6306. var internalFormat = this._gl.RGBA;
  6307. switch (format) {
  6308. case Engine.TEXTUREFORMAT_ALPHA:
  6309. internalFormat = this._gl.ALPHA;
  6310. break;
  6311. case Engine.TEXTUREFORMAT_LUMINANCE:
  6312. internalFormat = this._gl.LUMINANCE;
  6313. break;
  6314. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6315. internalFormat = this._gl.LUMINANCE_ALPHA;
  6316. break;
  6317. case Engine.TEXTUREFORMAT_RGB:
  6318. internalFormat = this._gl.RGB;
  6319. break;
  6320. case Engine.TEXTUREFORMAT_RGBA:
  6321. internalFormat = this._gl.RGBA;
  6322. break;
  6323. }
  6324. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6325. if (generateMipMaps) {
  6326. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6327. }
  6328. // Filters
  6329. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6330. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6332. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6333. this._activeTexturesCache = [];
  6334. texture._baseWidth = width;
  6335. texture._baseHeight = height;
  6336. texture._width = width;
  6337. texture._height = height;
  6338. texture.isReady = true;
  6339. texture.references = 1;
  6340. texture.samplingMode = samplingMode;
  6341. this._loadedTexturesCache.push(texture);
  6342. return texture;
  6343. };
  6344. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6345. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6346. var texture = this._gl.createTexture();
  6347. texture._baseWidth = width;
  6348. texture._baseHeight = height;
  6349. if (forceExponantOfTwo) {
  6350. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6351. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6352. }
  6353. this._activeTexturesCache = [];
  6354. texture._width = width;
  6355. texture._height = height;
  6356. texture.isReady = false;
  6357. texture.generateMipMaps = generateMipMaps;
  6358. texture.references = 1;
  6359. texture.samplingMode = samplingMode;
  6360. this.updateTextureSamplingMode(samplingMode, texture);
  6361. this._loadedTexturesCache.push(texture);
  6362. return texture;
  6363. };
  6364. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6365. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6366. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6367. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6368. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6369. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6370. };
  6371. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6372. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6373. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6374. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6375. if (texture.generateMipMaps) {
  6376. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6377. }
  6378. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6379. this._activeTexturesCache = [];
  6380. texture.isReady = true;
  6381. };
  6382. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6383. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6384. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6385. // Testing video texture support
  6386. if (this._videoTextureSupported === undefined) {
  6387. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6388. if (this._gl.getError() !== 0) {
  6389. this._videoTextureSupported = false;
  6390. }
  6391. else {
  6392. this._videoTextureSupported = true;
  6393. }
  6394. }
  6395. // Copy video through the current working canvas if video texture is not supported
  6396. if (!this._videoTextureSupported) {
  6397. if (!texture._workingCanvas) {
  6398. texture._workingCanvas = document.createElement("canvas");
  6399. texture._workingContext = texture._workingCanvas.getContext("2d");
  6400. texture._workingCanvas.width = texture._width;
  6401. texture._workingCanvas.height = texture._height;
  6402. }
  6403. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6404. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6405. }
  6406. else {
  6407. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6408. }
  6409. if (texture.generateMipMaps) {
  6410. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6411. }
  6412. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6413. this._activeTexturesCache = [];
  6414. texture.isReady = true;
  6415. };
  6416. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6417. // old version had a "generateMipMaps" arg instead of options.
  6418. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6419. // in the same way, generateDepthBuffer is defaulted to true
  6420. var generateMipMaps = false;
  6421. var generateDepthBuffer = true;
  6422. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6423. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6424. if (options !== undefined) {
  6425. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6426. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6427. type = options.type === undefined ? type : options.type;
  6428. if (options.samplingMode !== undefined) {
  6429. samplingMode = options.samplingMode;
  6430. }
  6431. if (type === Engine.TEXTURETYPE_FLOAT) {
  6432. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6433. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6434. }
  6435. }
  6436. var gl = this._gl;
  6437. var texture = gl.createTexture();
  6438. gl.bindTexture(gl.TEXTURE_2D, texture);
  6439. var width = size.width || size;
  6440. var height = size.height || size;
  6441. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6442. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6443. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6444. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6445. }
  6446. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6447. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6448. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6449. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6450. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6451. var depthBuffer;
  6452. // Create the depth buffer
  6453. if (generateDepthBuffer) {
  6454. depthBuffer = gl.createRenderbuffer();
  6455. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6456. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6457. }
  6458. // Create the framebuffer
  6459. var framebuffer = gl.createFramebuffer();
  6460. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6461. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6462. if (generateDepthBuffer) {
  6463. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6464. }
  6465. // Unbind
  6466. gl.bindTexture(gl.TEXTURE_2D, null);
  6467. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6468. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6469. texture._framebuffer = framebuffer;
  6470. if (generateDepthBuffer) {
  6471. texture._depthBuffer = depthBuffer;
  6472. }
  6473. texture._width = width;
  6474. texture._height = height;
  6475. texture.isReady = true;
  6476. texture.generateMipMaps = generateMipMaps;
  6477. texture.references = 1;
  6478. texture.samplingMode = samplingMode;
  6479. this._activeTexturesCache = [];
  6480. this._loadedTexturesCache.push(texture);
  6481. return texture;
  6482. };
  6483. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6484. var _this = this;
  6485. var gl = this._gl;
  6486. var texture = gl.createTexture();
  6487. texture.isCube = true;
  6488. texture.url = rootUrl;
  6489. texture.references = 1;
  6490. this._loadedTexturesCache.push(texture);
  6491. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6492. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6493. if (isDDS) {
  6494. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6495. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6496. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6497. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6498. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6499. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6500. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6501. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6502. }
  6503. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6504. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6505. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6506. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6507. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6508. _this._activeTexturesCache = [];
  6509. texture._width = info.width;
  6510. texture._height = info.height;
  6511. texture.isReady = true;
  6512. }, null, null, true);
  6513. }
  6514. else {
  6515. cascadeLoad(rootUrl, scene, function (imgs) {
  6516. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6517. var height = width;
  6518. _this._prepareWorkingCanvas();
  6519. _this._workingCanvas.width = width;
  6520. _this._workingCanvas.height = height;
  6521. var faces = [
  6522. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6523. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6524. ];
  6525. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6526. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6527. for (var index = 0; index < faces.length; index++) {
  6528. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6529. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6530. }
  6531. if (!noMipmap) {
  6532. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6533. }
  6534. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6535. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6536. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6538. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6539. _this._activeTexturesCache = [];
  6540. texture._width = width;
  6541. texture._height = height;
  6542. texture.isReady = true;
  6543. }, extensions);
  6544. }
  6545. return texture;
  6546. };
  6547. Engine.prototype._releaseTexture = function (texture) {
  6548. var gl = this._gl;
  6549. if (texture._framebuffer) {
  6550. gl.deleteFramebuffer(texture._framebuffer);
  6551. }
  6552. if (texture._depthBuffer) {
  6553. gl.deleteRenderbuffer(texture._depthBuffer);
  6554. }
  6555. gl.deleteTexture(texture);
  6556. // Unbind channels
  6557. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6558. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6559. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6560. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6561. this._activeTexturesCache[channel] = null;
  6562. }
  6563. var index = this._loadedTexturesCache.indexOf(texture);
  6564. if (index !== -1) {
  6565. this._loadedTexturesCache.splice(index, 1);
  6566. }
  6567. };
  6568. Engine.prototype.bindSamplers = function (effect) {
  6569. this._gl.useProgram(effect.getProgram());
  6570. var samplers = effect.getSamplers();
  6571. for (var index = 0; index < samplers.length; index++) {
  6572. var uniform = effect.getUniform(samplers[index]);
  6573. this._gl.uniform1i(uniform, index);
  6574. }
  6575. this._currentEffect = null;
  6576. };
  6577. Engine.prototype._bindTexture = function (channel, texture) {
  6578. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6579. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6580. this._activeTexturesCache[channel] = null;
  6581. };
  6582. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6583. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6584. };
  6585. Engine.prototype.setTexture = function (channel, texture) {
  6586. if (channel < 0) {
  6587. return;
  6588. }
  6589. // Not ready?
  6590. if (!texture || !texture.isReady()) {
  6591. if (this._activeTexturesCache[channel] != null) {
  6592. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6593. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6594. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6595. this._activeTexturesCache[channel] = null;
  6596. }
  6597. return;
  6598. }
  6599. // Video
  6600. if (texture instanceof BABYLON.VideoTexture) {
  6601. if (texture.update()) {
  6602. this._activeTexturesCache[channel] = null;
  6603. }
  6604. }
  6605. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6606. texture.delayLoad();
  6607. return;
  6608. }
  6609. if (this._activeTexturesCache[channel] === texture) {
  6610. return;
  6611. }
  6612. this._activeTexturesCache[channel] = texture;
  6613. var internalTexture = texture.getInternalTexture();
  6614. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6615. if (internalTexture.isCube) {
  6616. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6617. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6618. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6619. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6620. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6621. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6622. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6623. }
  6624. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6625. }
  6626. else {
  6627. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6628. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6629. internalTexture._cachedWrapU = texture.wrapU;
  6630. switch (texture.wrapU) {
  6631. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6632. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6633. break;
  6634. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6635. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6636. break;
  6637. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6638. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6639. break;
  6640. }
  6641. }
  6642. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6643. internalTexture._cachedWrapV = texture.wrapV;
  6644. switch (texture.wrapV) {
  6645. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6646. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6647. break;
  6648. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6649. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6650. break;
  6651. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6652. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6653. break;
  6654. }
  6655. }
  6656. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6657. }
  6658. };
  6659. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6660. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6661. var value = texture.anisotropicFilteringLevel;
  6662. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6663. value = 1;
  6664. }
  6665. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6666. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6667. texture._cachedAnisotropicFilteringLevel = value;
  6668. }
  6669. };
  6670. Engine.prototype.readPixels = function (x, y, width, height) {
  6671. var data = new Uint8Array(height * width * 4);
  6672. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6673. return data;
  6674. };
  6675. // Dispose
  6676. Engine.prototype.dispose = function () {
  6677. this.hideLoadingUI();
  6678. this.stopRenderLoop();
  6679. // Release scenes
  6680. while (this.scenes.length) {
  6681. this.scenes[0].dispose();
  6682. }
  6683. // Release audio engine
  6684. Engine.audioEngine.dispose();
  6685. // Release effects
  6686. for (var name in this._compiledEffects) {
  6687. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6688. }
  6689. // Unbind
  6690. for (var i in this._vertexAttribArrays) {
  6691. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6692. continue;
  6693. }
  6694. this._gl.disableVertexAttribArray(i);
  6695. }
  6696. // Events
  6697. window.removeEventListener("blur", this._onBlur);
  6698. window.removeEventListener("focus", this._onFocus);
  6699. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6700. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6701. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6702. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6703. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6704. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6705. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6706. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6707. };
  6708. // Loading screen
  6709. Engine.prototype.displayLoadingUI = function () {
  6710. var _this = this;
  6711. this._loadingDiv = document.createElement("div");
  6712. this._loadingDiv.style.opacity = "0";
  6713. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6714. // Loading text
  6715. this._loadingTextDiv = document.createElement("div");
  6716. this._loadingTextDiv.style.position = "absolute";
  6717. this._loadingTextDiv.style.left = "0";
  6718. this._loadingTextDiv.style.top = "50%";
  6719. this._loadingTextDiv.style.marginTop = "80px";
  6720. this._loadingTextDiv.style.width = "100%";
  6721. this._loadingTextDiv.style.height = "20px";
  6722. this._loadingTextDiv.style.fontFamily = "Arial";
  6723. this._loadingTextDiv.style.fontSize = "14px";
  6724. this._loadingTextDiv.style.color = "white";
  6725. this._loadingTextDiv.style.textAlign = "center";
  6726. this._loadingTextDiv.innerHTML = "Loading";
  6727. this._loadingDiv.appendChild(this._loadingTextDiv);
  6728. // Loading img
  6729. var imgBack = new Image();
  6730. 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==";
  6731. imgBack.style.position = "absolute";
  6732. imgBack.style.left = "50%";
  6733. imgBack.style.top = "50%";
  6734. imgBack.style.marginLeft = "-50px";
  6735. imgBack.style.marginTop = "-50px";
  6736. imgBack.style.transition = "transform 1.0s ease";
  6737. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6738. var deg = 360;
  6739. var onTransitionEnd = function () {
  6740. deg += 360;
  6741. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6742. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6743. };
  6744. imgBack.addEventListener("transitionend", onTransitionEnd);
  6745. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6746. this._loadingDiv.appendChild(imgBack);
  6747. // front image
  6748. var imgFront = new Image();
  6749. 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=";
  6750. imgFront.style.position = "absolute";
  6751. imgFront.style.left = "50%";
  6752. imgFront.style.top = "50%";
  6753. imgFront.style.marginLeft = "-50px";
  6754. imgFront.style.marginTop = "-50px";
  6755. this._loadingDiv.appendChild(imgFront);
  6756. // Resize
  6757. this._resizeLoadingUI = function () {
  6758. var canvasRect = _this.getRenderingCanvasClientRect();
  6759. _this._loadingDiv.style.position = "absolute";
  6760. _this._loadingDiv.style.left = canvasRect.left + "px";
  6761. _this._loadingDiv.style.top = canvasRect.top + "px";
  6762. _this._loadingDiv.style.width = canvasRect.width + "px";
  6763. _this._loadingDiv.style.height = canvasRect.height + "px";
  6764. };
  6765. this._resizeLoadingUI();
  6766. window.addEventListener("resize", this._resizeLoadingUI);
  6767. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6768. document.body.appendChild(this._loadingDiv);
  6769. setTimeout(function () {
  6770. _this._loadingDiv.style.opacity = "1";
  6771. imgBack.style.transform = "rotateZ(360deg)";
  6772. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6773. }, 0);
  6774. };
  6775. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6776. set: function (text) {
  6777. if (!this._loadingDiv) {
  6778. return;
  6779. }
  6780. this._loadingTextDiv.innerHTML = text;
  6781. },
  6782. enumerable: true,
  6783. configurable: true
  6784. });
  6785. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6786. get: function () {
  6787. return this._loadingDivBackgroundColor;
  6788. },
  6789. set: function (color) {
  6790. this._loadingDivBackgroundColor = color;
  6791. if (!this._loadingDiv) {
  6792. return;
  6793. }
  6794. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6795. },
  6796. enumerable: true,
  6797. configurable: true
  6798. });
  6799. Engine.prototype.hideLoadingUI = function () {
  6800. var _this = this;
  6801. if (!this._loadingDiv) {
  6802. return;
  6803. }
  6804. var onTransitionEnd = function () {
  6805. if (!_this._loadingDiv) {
  6806. return;
  6807. }
  6808. document.body.removeChild(_this._loadingDiv);
  6809. window.removeEventListener("resize", _this._resizeLoadingUI);
  6810. _this._loadingDiv = null;
  6811. };
  6812. this._loadingDiv.style.opacity = "0";
  6813. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6814. };
  6815. // FPS
  6816. Engine.prototype.getFps = function () {
  6817. return this.fps;
  6818. };
  6819. Engine.prototype.getDeltaTime = function () {
  6820. return this.deltaTime;
  6821. };
  6822. Engine.prototype._measureFps = function () {
  6823. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6824. var length = this.previousFramesDuration.length;
  6825. if (length >= 2) {
  6826. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6827. }
  6828. if (length >= this.fpsRange) {
  6829. if (length > this.fpsRange) {
  6830. this.previousFramesDuration.splice(0, 1);
  6831. length = this.previousFramesDuration.length;
  6832. }
  6833. var sum = 0;
  6834. for (var id = 0; id < length - 1; id++) {
  6835. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6836. }
  6837. this.fps = 1000.0 / (sum / (length - 1));
  6838. }
  6839. };
  6840. // Statics
  6841. Engine.isSupported = function () {
  6842. try {
  6843. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6844. if (navigator.isCocoonJS) {
  6845. return true;
  6846. }
  6847. var tempcanvas = document.createElement("canvas");
  6848. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6849. return gl != null && !!window.WebGLRenderingContext;
  6850. }
  6851. catch (e) {
  6852. return false;
  6853. }
  6854. };
  6855. // Const statics
  6856. Engine._ALPHA_DISABLE = 0;
  6857. Engine._ALPHA_ADD = 1;
  6858. Engine._ALPHA_COMBINE = 2;
  6859. Engine._DELAYLOADSTATE_NONE = 0;
  6860. Engine._DELAYLOADSTATE_LOADED = 1;
  6861. Engine._DELAYLOADSTATE_LOADING = 2;
  6862. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6863. Engine._TEXTUREFORMAT_ALPHA = 0;
  6864. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6865. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6866. Engine._TEXTUREFORMAT_RGB = 4;
  6867. Engine._TEXTUREFORMAT_RGBA = 4;
  6868. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6869. Engine._TEXTURETYPE_FLOAT = 1;
  6870. // Updatable statics so stick with vars here
  6871. Engine.Epsilon = 0.001;
  6872. Engine.CollisionsEpsilon = 0.001;
  6873. Engine.CodeRepository = "Babylon/";
  6874. Engine.ShadersRepository = "Babylon/Shaders/";
  6875. return Engine;
  6876. })();
  6877. BABYLON.Engine = Engine;
  6878. })(BABYLON || (BABYLON = {}));
  6879. //# sourceMappingURL=babylon.engine.js.map
  6880. var BABYLON;
  6881. (function (BABYLON) {
  6882. /**
  6883. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6884. */
  6885. var Node = (function () {
  6886. /**
  6887. * @constructor
  6888. * @param {string} name - the name and id to be given to this node
  6889. * @param {BABYLON.Scene} the scene this node will be added to
  6890. */
  6891. function Node(name, scene) {
  6892. this.state = "";
  6893. this.animations = new Array();
  6894. this._childrenFlag = -1;
  6895. this._isEnabled = true;
  6896. this._isReady = true;
  6897. this._currentRenderId = -1;
  6898. this._parentRenderId = -1;
  6899. this.name = name;
  6900. this.id = name;
  6901. this._scene = scene;
  6902. this._initCache();
  6903. }
  6904. Node.prototype.getScene = function () {
  6905. return this._scene;
  6906. };
  6907. Node.prototype.getEngine = function () {
  6908. return this._scene.getEngine();
  6909. };
  6910. // override it in derived class
  6911. Node.prototype.getWorldMatrix = function () {
  6912. return BABYLON.Matrix.Identity();
  6913. };
  6914. // override it in derived class if you add new variables to the cache
  6915. // and call the parent class method
  6916. Node.prototype._initCache = function () {
  6917. this._cache = {};
  6918. this._cache.parent = undefined;
  6919. };
  6920. Node.prototype.updateCache = function (force) {
  6921. if (!force && this.isSynchronized())
  6922. return;
  6923. this._cache.parent = this.parent;
  6924. this._updateCache();
  6925. };
  6926. // override it in derived class if you add new variables to the cache
  6927. // and call the parent class method if !ignoreParentClass
  6928. Node.prototype._updateCache = function (ignoreParentClass) {
  6929. };
  6930. // override it in derived class if you add new variables to the cache
  6931. Node.prototype._isSynchronized = function () {
  6932. return true;
  6933. };
  6934. Node.prototype._markSyncedWithParent = function () {
  6935. this._parentRenderId = this.parent._currentRenderId;
  6936. };
  6937. Node.prototype.isSynchronizedWithParent = function () {
  6938. if (!this.parent) {
  6939. return true;
  6940. }
  6941. if (this._parentRenderId !== this.parent._currentRenderId) {
  6942. return false;
  6943. }
  6944. return this.parent.isSynchronized();
  6945. };
  6946. Node.prototype.isSynchronized = function (updateCache) {
  6947. var check = this.hasNewParent();
  6948. check = check || !this.isSynchronizedWithParent();
  6949. check = check || !this._isSynchronized();
  6950. if (updateCache)
  6951. this.updateCache(true);
  6952. return !check;
  6953. };
  6954. Node.prototype.hasNewParent = function (update) {
  6955. if (this._cache.parent === this.parent)
  6956. return false;
  6957. if (update)
  6958. this._cache.parent = this.parent;
  6959. return true;
  6960. };
  6961. /**
  6962. * Is this node ready to be used/rendered
  6963. * @return {boolean} is it ready
  6964. */
  6965. Node.prototype.isReady = function () {
  6966. return this._isReady;
  6967. };
  6968. /**
  6969. * Is this node enabled.
  6970. * If the node has a parent and is enabled, the parent will be inspected as well.
  6971. * @return {boolean} whether this node (and its parent) is enabled.
  6972. * @see setEnabled
  6973. */
  6974. Node.prototype.isEnabled = function () {
  6975. if (!this._isEnabled) {
  6976. return false;
  6977. }
  6978. if (this.parent) {
  6979. return this.parent.isEnabled();
  6980. }
  6981. return true;
  6982. };
  6983. /**
  6984. * Set the enabled state of this node.
  6985. * @param {boolean} value - the new enabled state
  6986. * @see isEnabled
  6987. */
  6988. Node.prototype.setEnabled = function (value) {
  6989. this._isEnabled = value;
  6990. };
  6991. /**
  6992. * Is this node a descendant of the given node.
  6993. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6994. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6995. * @see parent
  6996. */
  6997. Node.prototype.isDescendantOf = function (ancestor) {
  6998. if (this.parent) {
  6999. if (this.parent === ancestor) {
  7000. return true;
  7001. }
  7002. return this.parent.isDescendantOf(ancestor);
  7003. }
  7004. return false;
  7005. };
  7006. Node.prototype._getDescendants = function (list, results) {
  7007. for (var index = 0; index < list.length; index++) {
  7008. var item = list[index];
  7009. if (item.isDescendantOf(this)) {
  7010. results.push(item);
  7011. }
  7012. }
  7013. };
  7014. /**
  7015. * Will return all nodes that have this node as parent.
  7016. * @return {BABYLON.Node[]} all children nodes of all types.
  7017. */
  7018. Node.prototype.getDescendants = function () {
  7019. var results = [];
  7020. this._getDescendants(this._scene.meshes, results);
  7021. this._getDescendants(this._scene.lights, results);
  7022. this._getDescendants(this._scene.cameras, results);
  7023. return results;
  7024. };
  7025. Node.prototype._setReady = function (state) {
  7026. if (state == this._isReady) {
  7027. return;
  7028. }
  7029. if (!state) {
  7030. this._isReady = false;
  7031. return;
  7032. }
  7033. this._isReady = true;
  7034. if (this.onReady) {
  7035. this.onReady(this);
  7036. }
  7037. };
  7038. return Node;
  7039. })();
  7040. BABYLON.Node = Node;
  7041. })(BABYLON || (BABYLON = {}));
  7042. //# sourceMappingURL=babylon.node.js.map
  7043. var BABYLON;
  7044. (function (BABYLON) {
  7045. var FilesInput = (function () {
  7046. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7047. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7048. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7049. this._engine = p_engine;
  7050. this._canvas = p_canvas;
  7051. this._currentScene = p_scene;
  7052. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7053. this._progressCallback = p_progressCallback;
  7054. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7055. this._textureLoadingCallback = p_textureLoadingCallback;
  7056. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7057. }
  7058. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7059. var _this = this;
  7060. if (p_elementToMonitor) {
  7061. this._elementToMonitor = p_elementToMonitor;
  7062. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7063. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7064. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7065. }
  7066. };
  7067. FilesInput.prototype.renderFunction = function () {
  7068. if (this._additionnalRenderLoopLogicCallback) {
  7069. this._additionnalRenderLoopLogicCallback();
  7070. }
  7071. if (this._currentScene) {
  7072. if (this._textureLoadingCallback) {
  7073. var remaining = this._currentScene.getWaitingItemsCount();
  7074. if (remaining > 0) {
  7075. this._textureLoadingCallback(remaining);
  7076. }
  7077. }
  7078. this._currentScene.render();
  7079. }
  7080. };
  7081. FilesInput.prototype.drag = function (e) {
  7082. e.stopPropagation();
  7083. e.preventDefault();
  7084. };
  7085. FilesInput.prototype.drop = function (eventDrop) {
  7086. eventDrop.stopPropagation();
  7087. eventDrop.preventDefault();
  7088. this.loadFiles(eventDrop);
  7089. };
  7090. FilesInput.prototype.loadFiles = function (event) {
  7091. if (this._startingProcessingFilesCallback)
  7092. this._startingProcessingFilesCallback();
  7093. // Handling data transfer via drag'n'drop
  7094. if (event && event.dataTransfer && event.dataTransfer.files) {
  7095. this._filesToLoad = event.dataTransfer.files;
  7096. }
  7097. // Handling files from input files
  7098. if (event && event.target && event.target.files) {
  7099. this._filesToLoad = event.target.files;
  7100. }
  7101. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7102. for (var i = 0; i < this._filesToLoad.length; i++) {
  7103. switch (this._filesToLoad[i].type) {
  7104. case "image/jpeg":
  7105. case "image/png":
  7106. case "image/bmp":
  7107. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7108. break;
  7109. case "image/targa":
  7110. case "image/vnd.ms-dds":
  7111. case "audio/wav":
  7112. case "audio/x-wav":
  7113. case "audio/mp3":
  7114. case "audio/mpeg":
  7115. case "audio/mpeg3":
  7116. case "audio/x-mpeg-3":
  7117. case "audio/ogg":
  7118. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7119. break;
  7120. default:
  7121. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7122. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7123. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  7124. this._sceneFileToLoad = this._filesToLoad[i];
  7125. }
  7126. break;
  7127. }
  7128. }
  7129. this.reload();
  7130. }
  7131. };
  7132. FilesInput.prototype.reload = function () {
  7133. var _this = this;
  7134. var that = this;
  7135. // If a ".babylon" file has been provided
  7136. if (this._sceneFileToLoad) {
  7137. if (this._currentScene) {
  7138. this._engine.stopRenderLoop();
  7139. this._currentScene.dispose();
  7140. }
  7141. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7142. that._currentScene = newScene;
  7143. // Wait for textures and shaders to be ready
  7144. that._currentScene.executeWhenReady(function () {
  7145. // Attach camera to canvas inputs
  7146. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7147. that._currentScene.createDefaultCameraOrLight();
  7148. }
  7149. that._currentScene.activeCamera.attachControl(that._canvas);
  7150. if (that._sceneLoadedCallback) {
  7151. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7152. }
  7153. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7154. });
  7155. }, function (progress) {
  7156. if (_this._progressCallback) {
  7157. _this._progressCallback(progress);
  7158. }
  7159. });
  7160. }
  7161. else {
  7162. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7163. }
  7164. };
  7165. FilesInput.FilesTextures = new Array();
  7166. FilesInput.FilesToLoad = new Array();
  7167. return FilesInput;
  7168. })();
  7169. BABYLON.FilesInput = FilesInput;
  7170. })(BABYLON || (BABYLON = {}));
  7171. //# sourceMappingURL=babylon.filesInput.js.map
  7172. var BABYLON;
  7173. (function (BABYLON) {
  7174. var IntersectionInfo = (function () {
  7175. function IntersectionInfo(bu, bv, distance) {
  7176. this.bu = bu;
  7177. this.bv = bv;
  7178. this.distance = distance;
  7179. this.faceId = 0;
  7180. this.subMeshId = 0;
  7181. }
  7182. return IntersectionInfo;
  7183. })();
  7184. BABYLON.IntersectionInfo = IntersectionInfo;
  7185. var PickingInfo = (function () {
  7186. function PickingInfo() {
  7187. this.hit = false;
  7188. this.distance = 0;
  7189. this.pickedPoint = null;
  7190. this.pickedMesh = null;
  7191. this.bu = 0;
  7192. this.bv = 0;
  7193. this.faceId = -1;
  7194. this.subMeshId = 0;
  7195. }
  7196. // Methods
  7197. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  7198. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7199. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7200. return null;
  7201. }
  7202. var indices = this.pickedMesh.getIndices();
  7203. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7204. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7205. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7206. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7207. normal0 = normal0.scale(this.bu);
  7208. normal1 = normal1.scale(this.bv);
  7209. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7210. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7211. if (useWorldCoordinates) {
  7212. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7213. }
  7214. return result;
  7215. };
  7216. PickingInfo.prototype.getTextureCoordinates = function () {
  7217. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7218. return null;
  7219. }
  7220. var indices = this.pickedMesh.getIndices();
  7221. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7222. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7223. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7224. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7225. uv0 = uv0.scale(this.bu);
  7226. uv1 = uv1.scale(this.bv);
  7227. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  7228. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7229. };
  7230. return PickingInfo;
  7231. })();
  7232. BABYLON.PickingInfo = PickingInfo;
  7233. })(BABYLON || (BABYLON = {}));
  7234. //# sourceMappingURL=babylon.pickingInfo.js.map
  7235. var BABYLON;
  7236. (function (BABYLON) {
  7237. var BoundingSphere = (function () {
  7238. function BoundingSphere(minimum, maximum) {
  7239. this.minimum = minimum;
  7240. this.maximum = maximum;
  7241. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7242. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7243. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7244. this.radius = distance * 0.5;
  7245. this.centerWorld = BABYLON.Vector3.Zero();
  7246. this._update(BABYLON.Matrix.Identity());
  7247. }
  7248. // Methods
  7249. BoundingSphere.prototype._update = function (world) {
  7250. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7251. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7252. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7253. };
  7254. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7255. for (var i = 0; i < 6; i++) {
  7256. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7257. return false;
  7258. }
  7259. return true;
  7260. };
  7261. BoundingSphere.prototype.intersectsPoint = function (point) {
  7262. var x = this.centerWorld.x - point.x;
  7263. var y = this.centerWorld.y - point.y;
  7264. var z = this.centerWorld.z - point.z;
  7265. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7266. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7267. return false;
  7268. return true;
  7269. };
  7270. // Statics
  7271. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7272. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7273. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7274. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7275. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7276. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7277. return false;
  7278. return true;
  7279. };
  7280. return BoundingSphere;
  7281. })();
  7282. BABYLON.BoundingSphere = BoundingSphere;
  7283. })(BABYLON || (BABYLON = {}));
  7284. //# sourceMappingURL=babylon.boundingSphere.js.map
  7285. var BABYLON;
  7286. (function (BABYLON) {
  7287. var BoundingBox = (function () {
  7288. function BoundingBox(minimum, maximum) {
  7289. this.minimum = minimum;
  7290. this.maximum = maximum;
  7291. this.vectors = new Array();
  7292. this.vectorsWorld = new Array();
  7293. // Bounding vectors
  7294. this.vectors.push(this.minimum.clone());
  7295. this.vectors.push(this.maximum.clone());
  7296. this.vectors.push(this.minimum.clone());
  7297. this.vectors[2].x = this.maximum.x;
  7298. this.vectors.push(this.minimum.clone());
  7299. this.vectors[3].y = this.maximum.y;
  7300. this.vectors.push(this.minimum.clone());
  7301. this.vectors[4].z = this.maximum.z;
  7302. this.vectors.push(this.maximum.clone());
  7303. this.vectors[5].z = this.minimum.z;
  7304. this.vectors.push(this.maximum.clone());
  7305. this.vectors[6].x = this.minimum.x;
  7306. this.vectors.push(this.maximum.clone());
  7307. this.vectors[7].y = this.minimum.y;
  7308. // OBB
  7309. this.center = this.maximum.add(this.minimum).scale(0.5);
  7310. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7311. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7312. // World
  7313. for (var index = 0; index < this.vectors.length; index++) {
  7314. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7315. }
  7316. this.minimumWorld = BABYLON.Vector3.Zero();
  7317. this.maximumWorld = BABYLON.Vector3.Zero();
  7318. this._update(BABYLON.Matrix.Identity());
  7319. }
  7320. // Methods
  7321. BoundingBox.prototype.getWorldMatrix = function () {
  7322. return this._worldMatrix;
  7323. };
  7324. BoundingBox.prototype._update = function (world) {
  7325. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7326. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7327. for (var index = 0; index < this.vectors.length; index++) {
  7328. var v = this.vectorsWorld[index];
  7329. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7330. if (v.x < this.minimumWorld.x)
  7331. this.minimumWorld.x = v.x;
  7332. if (v.y < this.minimumWorld.y)
  7333. this.minimumWorld.y = v.y;
  7334. if (v.z < this.minimumWorld.z)
  7335. this.minimumWorld.z = v.z;
  7336. if (v.x > this.maximumWorld.x)
  7337. this.maximumWorld.x = v.x;
  7338. if (v.y > this.maximumWorld.y)
  7339. this.maximumWorld.y = v.y;
  7340. if (v.z > this.maximumWorld.z)
  7341. this.maximumWorld.z = v.z;
  7342. }
  7343. // OBB
  7344. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7345. this.center.scaleInPlace(0.5);
  7346. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7347. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7348. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7349. this._worldMatrix = world;
  7350. };
  7351. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7352. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7353. };
  7354. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7355. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7356. };
  7357. BoundingBox.prototype.intersectsPoint = function (point) {
  7358. var delta = -BABYLON.Engine.Epsilon;
  7359. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7360. return false;
  7361. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7362. return false;
  7363. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7364. return false;
  7365. return true;
  7366. };
  7367. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7368. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7369. };
  7370. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7371. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7372. return false;
  7373. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7374. return false;
  7375. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7376. return false;
  7377. return true;
  7378. };
  7379. // Statics
  7380. BoundingBox.Intersects = function (box0, box1) {
  7381. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7382. return false;
  7383. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7384. return false;
  7385. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7386. return false;
  7387. return true;
  7388. };
  7389. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7390. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7391. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7392. return (num <= (sphereRadius * sphereRadius));
  7393. };
  7394. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7395. for (var p = 0; p < 6; p++) {
  7396. for (var i = 0; i < 8; i++) {
  7397. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7398. return false;
  7399. }
  7400. }
  7401. }
  7402. return true;
  7403. };
  7404. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7405. for (var p = 0; p < 6; p++) {
  7406. var inCount = 8;
  7407. for (var i = 0; i < 8; i++) {
  7408. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7409. --inCount;
  7410. }
  7411. else {
  7412. break;
  7413. }
  7414. }
  7415. if (inCount === 0)
  7416. return false;
  7417. }
  7418. return true;
  7419. };
  7420. return BoundingBox;
  7421. })();
  7422. BABYLON.BoundingBox = BoundingBox;
  7423. })(BABYLON || (BABYLON = {}));
  7424. //# sourceMappingURL=babylon.boundingBox.js.map
  7425. var BABYLON;
  7426. (function (BABYLON) {
  7427. var computeBoxExtents = function (axis, box) {
  7428. var p = BABYLON.Vector3.Dot(box.center, axis);
  7429. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7430. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7431. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7432. var r = r0 + r1 + r2;
  7433. return {
  7434. min: p - r,
  7435. max: p + r
  7436. };
  7437. };
  7438. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7439. var axisOverlap = function (axis, box0, box1) {
  7440. var result0 = computeBoxExtents(axis, box0);
  7441. var result1 = computeBoxExtents(axis, box1);
  7442. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7443. };
  7444. var BoundingInfo = (function () {
  7445. function BoundingInfo(minimum, maximum) {
  7446. this.minimum = minimum;
  7447. this.maximum = maximum;
  7448. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7449. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7450. }
  7451. // Methods
  7452. BoundingInfo.prototype._update = function (world) {
  7453. this.boundingBox._update(world);
  7454. this.boundingSphere._update(world);
  7455. };
  7456. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7457. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7458. return false;
  7459. return this.boundingBox.isInFrustum(frustumPlanes);
  7460. };
  7461. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7462. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7463. };
  7464. BoundingInfo.prototype._checkCollision = function (collider) {
  7465. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7466. };
  7467. BoundingInfo.prototype.intersectsPoint = function (point) {
  7468. if (!this.boundingSphere.centerWorld) {
  7469. return false;
  7470. }
  7471. if (!this.boundingSphere.intersectsPoint(point)) {
  7472. return false;
  7473. }
  7474. if (!this.boundingBox.intersectsPoint(point)) {
  7475. return false;
  7476. }
  7477. return true;
  7478. };
  7479. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7480. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7481. return false;
  7482. }
  7483. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7484. return false;
  7485. }
  7486. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7487. return false;
  7488. }
  7489. if (!precise) {
  7490. return true;
  7491. }
  7492. var box0 = this.boundingBox;
  7493. var box1 = boundingInfo.boundingBox;
  7494. if (!axisOverlap(box0.directions[0], box0, box1))
  7495. return false;
  7496. if (!axisOverlap(box0.directions[1], box0, box1))
  7497. return false;
  7498. if (!axisOverlap(box0.directions[2], box0, box1))
  7499. return false;
  7500. if (!axisOverlap(box1.directions[0], box0, box1))
  7501. return false;
  7502. if (!axisOverlap(box1.directions[1], box0, box1))
  7503. return false;
  7504. if (!axisOverlap(box1.directions[2], box0, box1))
  7505. return false;
  7506. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7507. return false;
  7508. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7509. return false;
  7510. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7511. return false;
  7512. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7513. return false;
  7514. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7515. return false;
  7516. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7517. return false;
  7518. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7519. return false;
  7520. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7521. return false;
  7522. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7523. return false;
  7524. return true;
  7525. };
  7526. return BoundingInfo;
  7527. })();
  7528. BABYLON.BoundingInfo = BoundingInfo;
  7529. })(BABYLON || (BABYLON = {}));
  7530. //# sourceMappingURL=babylon.boundingInfo.js.map
  7531. var __extends = this.__extends || function (d, b) {
  7532. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7533. function __() { this.constructor = d; }
  7534. __.prototype = b.prototype;
  7535. d.prototype = new __();
  7536. };
  7537. var BABYLON;
  7538. (function (BABYLON) {
  7539. var AbstractMesh = (function (_super) {
  7540. __extends(AbstractMesh, _super);
  7541. function AbstractMesh(name, scene) {
  7542. var _this = this;
  7543. _super.call(this, name, scene);
  7544. // Properties
  7545. this.definedFacingForward = true; // orientation for POV movement & rotation
  7546. this.position = new BABYLON.Vector3(0, 0, 0);
  7547. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7548. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7549. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7550. this.visibility = 1.0;
  7551. this.alphaIndex = Number.MAX_VALUE;
  7552. this.infiniteDistance = false;
  7553. this.isVisible = true;
  7554. this.isPickable = true;
  7555. this.showBoundingBox = false;
  7556. this.showSubMeshesBoundingBox = false;
  7557. this.onDispose = null;
  7558. this.checkCollisions = false;
  7559. this.isBlocker = false;
  7560. this.renderingGroupId = 0;
  7561. this.receiveShadows = false;
  7562. this.renderOutline = false;
  7563. this.outlineColor = BABYLON.Color3.Red();
  7564. this.outlineWidth = 0.02;
  7565. this.renderOverlay = false;
  7566. this.overlayColor = BABYLON.Color3.Red();
  7567. this.overlayAlpha = 0.5;
  7568. this.hasVertexAlpha = false;
  7569. this.useVertexColors = true;
  7570. this.applyFog = true;
  7571. this.useOctreeForRenderingSelection = true;
  7572. this.useOctreeForPicking = true;
  7573. this.useOctreeForCollisions = true;
  7574. this.layerMask = 0x0FFFFFFF;
  7575. this.alwaysSelectAsActiveMesh = false;
  7576. // Physics
  7577. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7578. // Collisions
  7579. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7580. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7581. this._collider = new BABYLON.Collider();
  7582. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7583. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7584. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7585. // Cache
  7586. this._localScaling = BABYLON.Matrix.Zero();
  7587. this._localRotation = BABYLON.Matrix.Zero();
  7588. this._localTranslation = BABYLON.Matrix.Zero();
  7589. this._localBillboard = BABYLON.Matrix.Zero();
  7590. this._localPivotScaling = BABYLON.Matrix.Zero();
  7591. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7592. this._localWorld = BABYLON.Matrix.Zero();
  7593. this._worldMatrix = BABYLON.Matrix.Zero();
  7594. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7595. this._absolutePosition = BABYLON.Vector3.Zero();
  7596. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7597. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7598. this._isDirty = false;
  7599. this._pivotMatrix = BABYLON.Matrix.Identity();
  7600. this._isDisposed = false;
  7601. this._renderId = 0;
  7602. this._intersectionsInProgress = new Array();
  7603. this._onAfterWorldMatrixUpdate = new Array();
  7604. this._isWorldMatrixFrozen = false;
  7605. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7606. if (collidedMesh === void 0) { collidedMesh = null; }
  7607. //TODO move this to the collision coordinator!
  7608. if (_this.getScene().workerCollisions)
  7609. newPosition.multiplyInPlace(_this._collider.radius);
  7610. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7611. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7612. _this.position.addInPlace(_this._diffPositionForCollisions);
  7613. }
  7614. };
  7615. scene.addMesh(this);
  7616. }
  7617. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7618. get: function () {
  7619. return AbstractMesh._BILLBOARDMODE_NONE;
  7620. },
  7621. enumerable: true,
  7622. configurable: true
  7623. });
  7624. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7625. get: function () {
  7626. return AbstractMesh._BILLBOARDMODE_X;
  7627. },
  7628. enumerable: true,
  7629. configurable: true
  7630. });
  7631. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7632. get: function () {
  7633. return AbstractMesh._BILLBOARDMODE_Y;
  7634. },
  7635. enumerable: true,
  7636. configurable: true
  7637. });
  7638. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7639. get: function () {
  7640. return AbstractMesh._BILLBOARDMODE_Z;
  7641. },
  7642. enumerable: true,
  7643. configurable: true
  7644. });
  7645. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7646. get: function () {
  7647. return AbstractMesh._BILLBOARDMODE_ALL;
  7648. },
  7649. enumerable: true,
  7650. configurable: true
  7651. });
  7652. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7653. // Methods
  7654. get: function () {
  7655. return false;
  7656. },
  7657. enumerable: true,
  7658. configurable: true
  7659. });
  7660. AbstractMesh.prototype.getLOD = function (camera) {
  7661. return this;
  7662. };
  7663. AbstractMesh.prototype.getTotalVertices = function () {
  7664. return 0;
  7665. };
  7666. AbstractMesh.prototype.getIndices = function () {
  7667. return null;
  7668. };
  7669. AbstractMesh.prototype.getVerticesData = function (kind) {
  7670. return null;
  7671. };
  7672. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7673. return false;
  7674. };
  7675. AbstractMesh.prototype.getBoundingInfo = function () {
  7676. if (this._masterMesh) {
  7677. return this._masterMesh.getBoundingInfo();
  7678. }
  7679. if (!this._boundingInfo) {
  7680. this._updateBoundingInfo();
  7681. }
  7682. return this._boundingInfo;
  7683. };
  7684. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7685. get: function () {
  7686. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7687. },
  7688. enumerable: true,
  7689. configurable: true
  7690. });
  7691. AbstractMesh.prototype._preActivate = function () {
  7692. };
  7693. AbstractMesh.prototype._activate = function (renderId) {
  7694. this._renderId = renderId;
  7695. };
  7696. AbstractMesh.prototype.getWorldMatrix = function () {
  7697. if (this._masterMesh) {
  7698. return this._masterMesh.getWorldMatrix();
  7699. }
  7700. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7701. this.computeWorldMatrix();
  7702. }
  7703. return this._worldMatrix;
  7704. };
  7705. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7706. get: function () {
  7707. return this._worldMatrix;
  7708. },
  7709. enumerable: true,
  7710. configurable: true
  7711. });
  7712. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7713. get: function () {
  7714. return this._absolutePosition;
  7715. },
  7716. enumerable: true,
  7717. configurable: true
  7718. });
  7719. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7720. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7721. this.computeWorldMatrix(true);
  7722. this._isWorldMatrixFrozen = true;
  7723. };
  7724. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7725. this._isWorldMatrixFrozen = false;
  7726. this.computeWorldMatrix(true);
  7727. };
  7728. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7729. get: function () {
  7730. return this._isWorldMatrixFrozen;
  7731. },
  7732. enumerable: true,
  7733. configurable: true
  7734. });
  7735. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7736. if (!this.rotationQuaternion) {
  7737. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7738. this.rotation = BABYLON.Vector3.Zero();
  7739. }
  7740. if (!space || space === BABYLON.Space.LOCAL) {
  7741. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7742. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7743. }
  7744. else {
  7745. if (this.parent) {
  7746. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7747. invertParentWorldMatrix.invert();
  7748. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7749. }
  7750. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7751. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7752. }
  7753. };
  7754. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7755. var displacementVector = axis.scale(distance);
  7756. if (!space || space === BABYLON.Space.LOCAL) {
  7757. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7758. this.setPositionWithLocalVector(tempV3);
  7759. }
  7760. else {
  7761. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7762. }
  7763. };
  7764. AbstractMesh.prototype.getAbsolutePosition = function () {
  7765. this.computeWorldMatrix();
  7766. return this._absolutePosition;
  7767. };
  7768. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7769. if (!absolutePosition) {
  7770. return;
  7771. }
  7772. var absolutePositionX;
  7773. var absolutePositionY;
  7774. var absolutePositionZ;
  7775. if (absolutePosition.x === undefined) {
  7776. if (arguments.length < 3) {
  7777. return;
  7778. }
  7779. absolutePositionX = arguments[0];
  7780. absolutePositionY = arguments[1];
  7781. absolutePositionZ = arguments[2];
  7782. }
  7783. else {
  7784. absolutePositionX = absolutePosition.x;
  7785. absolutePositionY = absolutePosition.y;
  7786. absolutePositionZ = absolutePosition.z;
  7787. }
  7788. if (this.parent) {
  7789. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7790. invertParentWorldMatrix.invert();
  7791. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7792. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7793. }
  7794. else {
  7795. this.position.x = absolutePositionX;
  7796. this.position.y = absolutePositionY;
  7797. this.position.z = absolutePositionZ;
  7798. }
  7799. };
  7800. // ================================== Point of View Movement =================================
  7801. /**
  7802. * Perform relative position change from the point of view of behind the front of the mesh.
  7803. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7804. * Supports definition of mesh facing forward or backward.
  7805. * @param {number} amountRight
  7806. * @param {number} amountUp
  7807. * @param {number} amountForward
  7808. */
  7809. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7810. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7811. };
  7812. /**
  7813. * Calculate relative position change from the point of view of behind the front of the mesh.
  7814. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7815. * Supports definition of mesh facing forward or backward.
  7816. * @param {number} amountRight
  7817. * @param {number} amountUp
  7818. * @param {number} amountForward
  7819. */
  7820. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7821. var rotMatrix = new BABYLON.Matrix();
  7822. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7823. rotQuaternion.toRotationMatrix(rotMatrix);
  7824. var translationDelta = BABYLON.Vector3.Zero();
  7825. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7826. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7827. return translationDelta;
  7828. };
  7829. // ================================== Point of View Rotation =================================
  7830. /**
  7831. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7832. * Supports definition of mesh facing forward or backward.
  7833. * @param {number} flipBack
  7834. * @param {number} twirlClockwise
  7835. * @param {number} tiltRight
  7836. */
  7837. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7838. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7839. };
  7840. /**
  7841. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7842. * Supports definition of mesh facing forward or backward.
  7843. * @param {number} flipBack
  7844. * @param {number} twirlClockwise
  7845. * @param {number} tiltRight
  7846. */
  7847. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7848. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7849. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7850. };
  7851. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7852. this._pivotMatrix = matrix;
  7853. this._cache.pivotMatrixUpdated = true;
  7854. };
  7855. AbstractMesh.prototype.getPivotMatrix = function () {
  7856. return this._pivotMatrix;
  7857. };
  7858. AbstractMesh.prototype._isSynchronized = function () {
  7859. if (this._isDirty) {
  7860. return false;
  7861. }
  7862. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7863. return false;
  7864. if (this._cache.pivotMatrixUpdated) {
  7865. return false;
  7866. }
  7867. if (this.infiniteDistance) {
  7868. return false;
  7869. }
  7870. if (!this._cache.position.equals(this.position))
  7871. return false;
  7872. if (this.rotationQuaternion) {
  7873. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7874. return false;
  7875. }
  7876. else {
  7877. if (!this._cache.rotation.equals(this.rotation))
  7878. return false;
  7879. }
  7880. if (!this._cache.scaling.equals(this.scaling))
  7881. return false;
  7882. return true;
  7883. };
  7884. AbstractMesh.prototype._initCache = function () {
  7885. _super.prototype._initCache.call(this);
  7886. this._cache.localMatrixUpdated = false;
  7887. this._cache.position = BABYLON.Vector3.Zero();
  7888. this._cache.scaling = BABYLON.Vector3.Zero();
  7889. this._cache.rotation = BABYLON.Vector3.Zero();
  7890. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7891. };
  7892. AbstractMesh.prototype.markAsDirty = function (property) {
  7893. if (property === "rotation") {
  7894. this.rotationQuaternion = null;
  7895. }
  7896. this._currentRenderId = Number.MAX_VALUE;
  7897. this._isDirty = true;
  7898. };
  7899. AbstractMesh.prototype._updateBoundingInfo = function () {
  7900. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7901. this._boundingInfo._update(this.worldMatrixFromCache);
  7902. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7903. };
  7904. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7905. if (!this.subMeshes) {
  7906. return;
  7907. }
  7908. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7909. var subMesh = this.subMeshes[subIndex];
  7910. subMesh.updateBoundingInfo(matrix);
  7911. }
  7912. };
  7913. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7914. if (this._isWorldMatrixFrozen) {
  7915. return this._worldMatrix;
  7916. }
  7917. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7918. return this._worldMatrix;
  7919. }
  7920. this._cache.position.copyFrom(this.position);
  7921. this._cache.scaling.copyFrom(this.scaling);
  7922. this._cache.pivotMatrixUpdated = false;
  7923. this._currentRenderId = this.getScene().getRenderId();
  7924. this._isDirty = false;
  7925. // Scaling
  7926. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7927. // Rotation
  7928. if (this.rotationQuaternion) {
  7929. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7930. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7931. }
  7932. else {
  7933. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7934. this._cache.rotation.copyFrom(this.rotation);
  7935. }
  7936. // Translation
  7937. if (this.infiniteDistance && !this.parent) {
  7938. var camera = this.getScene().activeCamera;
  7939. var cameraWorldMatrix = camera.getWorldMatrix();
  7940. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7941. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7942. }
  7943. else {
  7944. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7945. }
  7946. // Composing transformations
  7947. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7948. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7949. // Billboarding
  7950. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7951. var localPosition = this.position.clone();
  7952. var zero = this.getScene().activeCamera.globalPosition.clone();
  7953. if (this.parent && this.parent.position) {
  7954. localPosition.addInPlace(this.parent.position);
  7955. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7956. }
  7957. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  7958. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7959. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7960. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7961. zero.y = localPosition.y + 0.001;
  7962. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7963. zero.z = localPosition.z + 0.001;
  7964. }
  7965. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7966. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7967. this._localBillboard.invert();
  7968. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7969. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7970. }
  7971. // Local world
  7972. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7973. // Parent
  7974. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7975. this._markSyncedWithParent();
  7976. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7977. }
  7978. else {
  7979. this._worldMatrix.copyFrom(this._localWorld);
  7980. }
  7981. // Bounding info
  7982. this._updateBoundingInfo();
  7983. // Absolute position
  7984. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7985. // Callbacks
  7986. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7987. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7988. }
  7989. return this._worldMatrix;
  7990. };
  7991. /**
  7992. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7993. * @param func: callback function to add
  7994. */
  7995. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7996. this._onAfterWorldMatrixUpdate.push(func);
  7997. };
  7998. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7999. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8000. if (index > -1) {
  8001. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8002. }
  8003. };
  8004. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8005. this.computeWorldMatrix();
  8006. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8007. };
  8008. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8009. this.computeWorldMatrix();
  8010. var invLocalWorldMatrix = this._localWorld.clone();
  8011. invLocalWorldMatrix.invert();
  8012. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8013. };
  8014. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8015. this.computeWorldMatrix(true);
  8016. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8017. };
  8018. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8019. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8020. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8021. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8022. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8023. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8024. /// <returns>Mesh oriented towards targetMesh</returns>
  8025. yawCor = yawCor || 0; // default to zero if undefined
  8026. pitchCor = pitchCor || 0;
  8027. rollCor = rollCor || 0;
  8028. var dv = targetPoint.subtract(this.position);
  8029. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8030. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8031. var pitch = Math.atan2(dv.y, len);
  8032. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8033. };
  8034. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8035. return this._boundingInfo.isInFrustum(frustumPlanes);
  8036. };
  8037. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8038. if (!camera) {
  8039. camera = this.getScene().activeCamera;
  8040. }
  8041. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8042. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8043. return false;
  8044. }
  8045. return true;
  8046. };
  8047. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8048. if (!this._boundingInfo || !mesh._boundingInfo) {
  8049. return false;
  8050. }
  8051. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8052. };
  8053. AbstractMesh.prototype.intersectsPoint = function (point) {
  8054. if (!this._boundingInfo) {
  8055. return false;
  8056. }
  8057. return this._boundingInfo.intersectsPoint(point);
  8058. };
  8059. // Physics
  8060. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8061. var physicsEngine = this.getScene().getPhysicsEngine();
  8062. if (!physicsEngine) {
  8063. return;
  8064. }
  8065. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8066. if (impostor.impostor) {
  8067. // Old API
  8068. options = impostor;
  8069. impostor = impostor.impostor;
  8070. }
  8071. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8072. physicsEngine._unregisterMesh(this);
  8073. return;
  8074. }
  8075. if (!options) {
  8076. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8077. }
  8078. else {
  8079. if (!options.mass && options.mass !== 0)
  8080. options.mass = 0;
  8081. if (!options.friction && options.friction !== 0)
  8082. options.friction = 0.2;
  8083. if (!options.restitution && options.restitution !== 0)
  8084. options.restitution = 0.2;
  8085. }
  8086. this._physicImpostor = impostor;
  8087. this._physicsMass = options.mass;
  8088. this._physicsFriction = options.friction;
  8089. this._physicRestitution = options.restitution;
  8090. return physicsEngine._registerMesh(this, impostor, options);
  8091. };
  8092. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8093. if (!this._physicImpostor) {
  8094. return BABYLON.PhysicsEngine.NoImpostor;
  8095. }
  8096. return this._physicImpostor;
  8097. };
  8098. AbstractMesh.prototype.getPhysicsMass = function () {
  8099. if (!this._physicsMass) {
  8100. return 0;
  8101. }
  8102. return this._physicsMass;
  8103. };
  8104. AbstractMesh.prototype.getPhysicsFriction = function () {
  8105. if (!this._physicsFriction) {
  8106. return 0;
  8107. }
  8108. return this._physicsFriction;
  8109. };
  8110. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8111. if (!this._physicRestitution) {
  8112. return 0;
  8113. }
  8114. return this._physicRestitution;
  8115. };
  8116. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8117. if (!camera) {
  8118. camera = this.getScene().activeCamera;
  8119. }
  8120. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8121. };
  8122. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8123. if (!camera) {
  8124. camera = this.getScene().activeCamera;
  8125. }
  8126. return this.absolutePosition.subtract(camera.position).length();
  8127. };
  8128. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8129. if (!this._physicImpostor) {
  8130. return;
  8131. }
  8132. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8133. };
  8134. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8135. if (!this._physicImpostor) {
  8136. return;
  8137. }
  8138. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8139. };
  8140. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8141. if (!this._physicImpostor) {
  8142. return;
  8143. }
  8144. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8145. };
  8146. // Collisions
  8147. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8148. var globalPosition = this.getAbsolutePosition();
  8149. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8150. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8151. this._collider.radius = this.ellipsoid;
  8152. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8153. };
  8154. // Submeshes octree
  8155. /**
  8156. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8157. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8158. */
  8159. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8160. if (maxCapacity === void 0) { maxCapacity = 64; }
  8161. if (maxDepth === void 0) { maxDepth = 2; }
  8162. if (!this._submeshesOctree) {
  8163. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8164. }
  8165. this.computeWorldMatrix(true);
  8166. // Update octree
  8167. var bbox = this.getBoundingInfo().boundingBox;
  8168. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8169. return this._submeshesOctree;
  8170. };
  8171. // Collisions
  8172. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8173. this._generatePointsArray();
  8174. // Transformation
  8175. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8176. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8177. subMesh._lastColliderWorldVertices = [];
  8178. subMesh._trianglePlanes = [];
  8179. var start = subMesh.verticesStart;
  8180. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8181. for (var i = start; i < end; i++) {
  8182. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8183. }
  8184. }
  8185. // Collide
  8186. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8187. if (collider.collisionFound) {
  8188. collider.collidedMesh = this;
  8189. }
  8190. };
  8191. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8192. var subMeshes;
  8193. var len;
  8194. // Octrees
  8195. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8196. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8197. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8198. len = intersections.length;
  8199. subMeshes = intersections.data;
  8200. }
  8201. else {
  8202. subMeshes = this.subMeshes;
  8203. len = subMeshes.length;
  8204. }
  8205. for (var index = 0; index < len; index++) {
  8206. var subMesh = subMeshes[index];
  8207. // Bounding test
  8208. if (len > 1 && !subMesh._checkCollision(collider))
  8209. continue;
  8210. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8211. }
  8212. };
  8213. AbstractMesh.prototype._checkCollision = function (collider) {
  8214. // Bounding box test
  8215. if (!this._boundingInfo._checkCollision(collider))
  8216. return;
  8217. // Transformation matrix
  8218. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8219. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8220. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8221. };
  8222. // Picking
  8223. AbstractMesh.prototype._generatePointsArray = function () {
  8224. return false;
  8225. };
  8226. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8227. var pickingInfo = new BABYLON.PickingInfo();
  8228. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8229. return pickingInfo;
  8230. }
  8231. if (!this._generatePointsArray()) {
  8232. return pickingInfo;
  8233. }
  8234. var intersectInfo = null;
  8235. // Octrees
  8236. var subMeshes;
  8237. var len;
  8238. if (this._submeshesOctree && this.useOctreeForPicking) {
  8239. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8240. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8241. len = intersections.length;
  8242. subMeshes = intersections.data;
  8243. }
  8244. else {
  8245. subMeshes = this.subMeshes;
  8246. len = subMeshes.length;
  8247. }
  8248. for (var index = 0; index < len; index++) {
  8249. var subMesh = subMeshes[index];
  8250. // Bounding test
  8251. if (len > 1 && !subMesh.canIntersects(ray))
  8252. continue;
  8253. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8254. if (currentIntersectInfo) {
  8255. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8256. intersectInfo = currentIntersectInfo;
  8257. intersectInfo.subMeshId = index;
  8258. if (fastCheck) {
  8259. break;
  8260. }
  8261. }
  8262. }
  8263. }
  8264. if (intersectInfo) {
  8265. // Get picked point
  8266. var world = this.getWorldMatrix();
  8267. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8268. var direction = ray.direction.clone();
  8269. direction = direction.scale(intersectInfo.distance);
  8270. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8271. var pickedPoint = worldOrigin.add(worldDirection);
  8272. // Return result
  8273. pickingInfo.hit = true;
  8274. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8275. pickingInfo.pickedPoint = pickedPoint;
  8276. pickingInfo.pickedMesh = this;
  8277. pickingInfo.bu = intersectInfo.bu;
  8278. pickingInfo.bv = intersectInfo.bv;
  8279. pickingInfo.faceId = intersectInfo.faceId;
  8280. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8281. return pickingInfo;
  8282. }
  8283. return pickingInfo;
  8284. };
  8285. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8286. return null;
  8287. };
  8288. AbstractMesh.prototype.releaseSubMeshes = function () {
  8289. if (this.subMeshes) {
  8290. while (this.subMeshes.length) {
  8291. this.subMeshes[0].dispose();
  8292. }
  8293. }
  8294. else {
  8295. this.subMeshes = new Array();
  8296. }
  8297. };
  8298. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8299. var index;
  8300. // Physics
  8301. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8302. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8303. }
  8304. // Intersections in progress
  8305. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8306. var other = this._intersectionsInProgress[index];
  8307. var pos = other._intersectionsInProgress.indexOf(this);
  8308. other._intersectionsInProgress.splice(pos, 1);
  8309. }
  8310. this._intersectionsInProgress = [];
  8311. // SubMeshes
  8312. this.releaseSubMeshes();
  8313. // Remove from scene
  8314. this.getScene().removeMesh(this);
  8315. if (!doNotRecurse) {
  8316. // Particles
  8317. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8318. if (this.getScene().particleSystems[index].emitter === this) {
  8319. this.getScene().particleSystems[index].dispose();
  8320. index--;
  8321. }
  8322. }
  8323. // Children
  8324. var objects = this.getScene().meshes.slice(0);
  8325. for (index = 0; index < objects.length; index++) {
  8326. if (objects[index].parent === this) {
  8327. objects[index].dispose();
  8328. }
  8329. }
  8330. }
  8331. else {
  8332. for (index = 0; index < this.getScene().meshes.length; index++) {
  8333. var obj = this.getScene().meshes[index];
  8334. if (obj.parent === this) {
  8335. obj.parent = null;
  8336. obj.computeWorldMatrix(true);
  8337. }
  8338. }
  8339. }
  8340. this._onAfterWorldMatrixUpdate = [];
  8341. this._isDisposed = true;
  8342. // Callback
  8343. if (this.onDispose) {
  8344. this.onDispose();
  8345. }
  8346. };
  8347. // Statics
  8348. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8349. AbstractMesh._BILLBOARDMODE_X = 1;
  8350. AbstractMesh._BILLBOARDMODE_Y = 2;
  8351. AbstractMesh._BILLBOARDMODE_Z = 4;
  8352. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8353. return AbstractMesh;
  8354. })(BABYLON.Node);
  8355. BABYLON.AbstractMesh = AbstractMesh;
  8356. })(BABYLON || (BABYLON = {}));
  8357. //# sourceMappingURL=babylon.abstractMesh.js.map
  8358. var __extends = this.__extends || function (d, b) {
  8359. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8360. function __() { this.constructor = d; }
  8361. __.prototype = b.prototype;
  8362. d.prototype = new __();
  8363. };
  8364. var BABYLON;
  8365. (function (BABYLON) {
  8366. var Light = (function (_super) {
  8367. __extends(Light, _super);
  8368. function Light(name, scene) {
  8369. _super.call(this, name, scene);
  8370. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8371. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8372. this.intensity = 1.0;
  8373. this.range = Number.MAX_VALUE;
  8374. this.includeOnlyWithLayerMask = 0;
  8375. this.includedOnlyMeshes = new Array();
  8376. this.excludedMeshes = new Array();
  8377. this.excludeWithLayerMask = 0;
  8378. this._excludedMeshesIds = new Array();
  8379. this._includedOnlyMeshesIds = new Array();
  8380. scene.addLight(this);
  8381. }
  8382. Light.prototype.getShadowGenerator = function () {
  8383. return this._shadowGenerator;
  8384. };
  8385. Light.prototype.getAbsolutePosition = function () {
  8386. return BABYLON.Vector3.Zero();
  8387. };
  8388. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8389. };
  8390. Light.prototype._getWorldMatrix = function () {
  8391. return BABYLON.Matrix.Identity();
  8392. };
  8393. Light.prototype.canAffectMesh = function (mesh) {
  8394. if (!mesh) {
  8395. return true;
  8396. }
  8397. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8398. return false;
  8399. }
  8400. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8401. return false;
  8402. }
  8403. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8404. return false;
  8405. }
  8406. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8407. return false;
  8408. }
  8409. return true;
  8410. };
  8411. Light.prototype.getWorldMatrix = function () {
  8412. this._currentRenderId = this.getScene().getRenderId();
  8413. var worldMatrix = this._getWorldMatrix();
  8414. if (this.parent && this.parent.getWorldMatrix) {
  8415. if (!this._parentedWorldMatrix) {
  8416. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8417. }
  8418. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8419. this._markSyncedWithParent();
  8420. return this._parentedWorldMatrix;
  8421. }
  8422. return worldMatrix;
  8423. };
  8424. Light.prototype.dispose = function () {
  8425. if (this._shadowGenerator) {
  8426. this._shadowGenerator.dispose();
  8427. this._shadowGenerator = null;
  8428. }
  8429. // Remove from scene
  8430. this.getScene().removeLight(this);
  8431. };
  8432. return Light;
  8433. })(BABYLON.Node);
  8434. BABYLON.Light = Light;
  8435. })(BABYLON || (BABYLON = {}));
  8436. //# sourceMappingURL=babylon.light.js.map
  8437. var __extends = this.__extends || function (d, b) {
  8438. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8439. function __() { this.constructor = d; }
  8440. __.prototype = b.prototype;
  8441. d.prototype = new __();
  8442. };
  8443. var BABYLON;
  8444. (function (BABYLON) {
  8445. var PointLight = (function (_super) {
  8446. __extends(PointLight, _super);
  8447. function PointLight(name, position, scene) {
  8448. _super.call(this, name, scene);
  8449. this.position = position;
  8450. }
  8451. PointLight.prototype.getAbsolutePosition = function () {
  8452. return this._transformedPosition ? this._transformedPosition : this.position;
  8453. };
  8454. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8455. if (this.parent && this.parent.getWorldMatrix) {
  8456. if (!this._transformedPosition) {
  8457. this._transformedPosition = BABYLON.Vector3.Zero();
  8458. }
  8459. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8460. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8461. return;
  8462. }
  8463. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8464. };
  8465. PointLight.prototype.getShadowGenerator = function () {
  8466. return null;
  8467. };
  8468. PointLight.prototype._getWorldMatrix = function () {
  8469. if (!this._worldMatrix) {
  8470. this._worldMatrix = BABYLON.Matrix.Identity();
  8471. }
  8472. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8473. return this._worldMatrix;
  8474. };
  8475. return PointLight;
  8476. })(BABYLON.Light);
  8477. BABYLON.PointLight = PointLight;
  8478. })(BABYLON || (BABYLON = {}));
  8479. //# sourceMappingURL=babylon.pointLight.js.map
  8480. var __extends = this.__extends || function (d, b) {
  8481. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8482. function __() { this.constructor = d; }
  8483. __.prototype = b.prototype;
  8484. d.prototype = new __();
  8485. };
  8486. var BABYLON;
  8487. (function (BABYLON) {
  8488. var SpotLight = (function (_super) {
  8489. __extends(SpotLight, _super);
  8490. function SpotLight(name, position, direction, angle, exponent, scene) {
  8491. _super.call(this, name, scene);
  8492. this.position = position;
  8493. this.direction = direction;
  8494. this.angle = angle;
  8495. this.exponent = exponent;
  8496. }
  8497. SpotLight.prototype.getAbsolutePosition = function () {
  8498. return this.transformedPosition ? this.transformedPosition : this.position;
  8499. };
  8500. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8501. var activeCamera = this.getScene().activeCamera;
  8502. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8503. };
  8504. SpotLight.prototype.supportsVSM = function () {
  8505. return true;
  8506. };
  8507. SpotLight.prototype.needRefreshPerFrame = function () {
  8508. return false;
  8509. };
  8510. SpotLight.prototype.setDirectionToTarget = function (target) {
  8511. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8512. return this.direction;
  8513. };
  8514. SpotLight.prototype.computeTransformedPosition = function () {
  8515. if (this.parent && this.parent.getWorldMatrix) {
  8516. if (!this.transformedPosition) {
  8517. this.transformedPosition = BABYLON.Vector3.Zero();
  8518. }
  8519. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8520. return true;
  8521. }
  8522. return false;
  8523. };
  8524. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8525. var normalizeDirection;
  8526. if (this.parent && this.parent.getWorldMatrix) {
  8527. if (!this._transformedDirection) {
  8528. this._transformedDirection = BABYLON.Vector3.Zero();
  8529. }
  8530. this.computeTransformedPosition();
  8531. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8532. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8533. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8534. }
  8535. else {
  8536. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8537. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8538. }
  8539. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8540. };
  8541. SpotLight.prototype._getWorldMatrix = function () {
  8542. if (!this._worldMatrix) {
  8543. this._worldMatrix = BABYLON.Matrix.Identity();
  8544. }
  8545. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8546. return this._worldMatrix;
  8547. };
  8548. return SpotLight;
  8549. })(BABYLON.Light);
  8550. BABYLON.SpotLight = SpotLight;
  8551. })(BABYLON || (BABYLON = {}));
  8552. //# sourceMappingURL=babylon.spotLight.js.map
  8553. var __extends = this.__extends || function (d, b) {
  8554. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8555. function __() { this.constructor = d; }
  8556. __.prototype = b.prototype;
  8557. d.prototype = new __();
  8558. };
  8559. var BABYLON;
  8560. (function (BABYLON) {
  8561. var HemisphericLight = (function (_super) {
  8562. __extends(HemisphericLight, _super);
  8563. function HemisphericLight(name, direction, scene) {
  8564. _super.call(this, name, scene);
  8565. this.direction = direction;
  8566. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8567. }
  8568. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8569. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8570. return this.direction;
  8571. };
  8572. HemisphericLight.prototype.getShadowGenerator = function () {
  8573. return null;
  8574. };
  8575. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8576. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8577. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8578. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8579. };
  8580. HemisphericLight.prototype._getWorldMatrix = function () {
  8581. if (!this._worldMatrix) {
  8582. this._worldMatrix = BABYLON.Matrix.Identity();
  8583. }
  8584. return this._worldMatrix;
  8585. };
  8586. return HemisphericLight;
  8587. })(BABYLON.Light);
  8588. BABYLON.HemisphericLight = HemisphericLight;
  8589. })(BABYLON || (BABYLON = {}));
  8590. //# sourceMappingURL=babylon.hemisphericLight.js.map
  8591. var __extends = this.__extends || function (d, b) {
  8592. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8593. function __() { this.constructor = d; }
  8594. __.prototype = b.prototype;
  8595. d.prototype = new __();
  8596. };
  8597. var BABYLON;
  8598. (function (BABYLON) {
  8599. var DirectionalLight = (function (_super) {
  8600. __extends(DirectionalLight, _super);
  8601. function DirectionalLight(name, direction, scene) {
  8602. _super.call(this, name, scene);
  8603. this.direction = direction;
  8604. this.shadowOrthoScale = 0.5;
  8605. this.position = direction.scale(-1);
  8606. }
  8607. DirectionalLight.prototype.getAbsolutePosition = function () {
  8608. return this.transformedPosition ? this.transformedPosition : this.position;
  8609. };
  8610. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8611. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8612. return this.direction;
  8613. };
  8614. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8615. var orthoLeft = Number.MAX_VALUE;
  8616. var orthoRight = Number.MIN_VALUE;
  8617. var orthoTop = Number.MIN_VALUE;
  8618. var orthoBottom = Number.MAX_VALUE;
  8619. var tempVector3 = BABYLON.Vector3.Zero();
  8620. var activeCamera = this.getScene().activeCamera;
  8621. // Check extends
  8622. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8623. var mesh = renderList[meshIndex];
  8624. if (!mesh) {
  8625. continue;
  8626. }
  8627. var boundingInfo = mesh.getBoundingInfo();
  8628. if (!boundingInfo) {
  8629. continue;
  8630. }
  8631. var boundingBox = boundingInfo.boundingBox;
  8632. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8633. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8634. if (tempVector3.x < orthoLeft)
  8635. orthoLeft = tempVector3.x;
  8636. if (tempVector3.y < orthoBottom)
  8637. orthoBottom = tempVector3.y;
  8638. if (tempVector3.x > orthoRight)
  8639. orthoRight = tempVector3.x;
  8640. if (tempVector3.y > orthoTop)
  8641. orthoTop = tempVector3.y;
  8642. }
  8643. }
  8644. var xOffset = orthoRight - orthoLeft;
  8645. var yOffset = orthoTop - orthoBottom;
  8646. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8647. };
  8648. DirectionalLight.prototype.supportsVSM = function () {
  8649. return true;
  8650. };
  8651. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8652. return true;
  8653. };
  8654. DirectionalLight.prototype.computeTransformedPosition = function () {
  8655. if (this.parent && this.parent.getWorldMatrix) {
  8656. if (!this.transformedPosition) {
  8657. this.transformedPosition = BABYLON.Vector3.Zero();
  8658. }
  8659. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8660. return true;
  8661. }
  8662. return false;
  8663. };
  8664. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8665. if (this.parent && this.parent.getWorldMatrix) {
  8666. if (!this._transformedDirection) {
  8667. this._transformedDirection = BABYLON.Vector3.Zero();
  8668. }
  8669. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8670. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8671. return;
  8672. }
  8673. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8674. };
  8675. DirectionalLight.prototype._getWorldMatrix = function () {
  8676. if (!this._worldMatrix) {
  8677. this._worldMatrix = BABYLON.Matrix.Identity();
  8678. }
  8679. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8680. return this._worldMatrix;
  8681. };
  8682. return DirectionalLight;
  8683. })(BABYLON.Light);
  8684. BABYLON.DirectionalLight = DirectionalLight;
  8685. })(BABYLON || (BABYLON = {}));
  8686. //# sourceMappingURL=babylon.directionalLight.js.map
  8687. var BABYLON;
  8688. (function (BABYLON) {
  8689. var ShadowGenerator = (function () {
  8690. function ShadowGenerator(mapSize, light) {
  8691. var _this = this;
  8692. // Members
  8693. this._filter = ShadowGenerator.FILTER_NONE;
  8694. this.blurScale = 2;
  8695. this._blurBoxOffset = 0;
  8696. this._bias = 0.00005;
  8697. this._darkness = 0;
  8698. this._transparencyShadow = false;
  8699. this._viewMatrix = BABYLON.Matrix.Zero();
  8700. this._projectionMatrix = BABYLON.Matrix.Zero();
  8701. this._transformMatrix = BABYLON.Matrix.Zero();
  8702. this._worldViewProjection = BABYLON.Matrix.Zero();
  8703. this._light = light;
  8704. this._scene = light.getScene();
  8705. this._mapSize = mapSize;
  8706. light._shadowGenerator = this;
  8707. // Render target
  8708. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8709. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8710. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8711. this._shadowMap.anisotropicFilteringLevel = 1;
  8712. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8713. this._shadowMap.renderParticles = false;
  8714. this._shadowMap.onAfterUnbind = function () {
  8715. if (!_this.useBlurVarianceShadowMap) {
  8716. return;
  8717. }
  8718. if (!_this._shadowMap2) {
  8719. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8720. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8721. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8722. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8723. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8724. _this._downSamplePostprocess.onApply = function (effect) {
  8725. effect.setTexture("textureSampler", _this._shadowMap);
  8726. };
  8727. _this.blurBoxOffset = 1;
  8728. }
  8729. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8730. };
  8731. // Custom render function
  8732. var renderSubMesh = function (subMesh) {
  8733. var mesh = subMesh.getRenderingMesh();
  8734. var scene = _this._scene;
  8735. var engine = scene.getEngine();
  8736. // Culling
  8737. engine.setState(subMesh.getMaterial().backFaceCulling);
  8738. // Managing instances
  8739. var batch = mesh._getInstancesRenderList(subMesh._id);
  8740. if (batch.mustReturn) {
  8741. return;
  8742. }
  8743. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8744. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8745. engine.enableEffect(_this._effect);
  8746. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8747. var material = subMesh.getMaterial();
  8748. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8749. // Alpha test
  8750. if (material && material.needAlphaTesting()) {
  8751. var alphaTexture = material.getAlphaTestTexture();
  8752. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8753. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8754. }
  8755. // Bones
  8756. if (mesh.useBones) {
  8757. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8758. }
  8759. // Draw
  8760. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8761. }
  8762. else {
  8763. // Need to reset refresh rate of the shadowMap
  8764. _this._shadowMap.resetRefreshCounter();
  8765. }
  8766. };
  8767. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8768. var index;
  8769. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8770. renderSubMesh(opaqueSubMeshes.data[index]);
  8771. }
  8772. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8773. renderSubMesh(alphaTestSubMeshes.data[index]);
  8774. }
  8775. if (_this._transparencyShadow) {
  8776. for (index = 0; index < transparentSubMeshes.length; index++) {
  8777. renderSubMesh(transparentSubMeshes.data[index]);
  8778. }
  8779. }
  8780. };
  8781. this._shadowMap.onClear = function (engine) {
  8782. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8783. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8784. }
  8785. else {
  8786. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8787. }
  8788. };
  8789. }
  8790. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8791. // Static
  8792. get: function () {
  8793. return ShadowGenerator._FILTER_NONE;
  8794. },
  8795. enumerable: true,
  8796. configurable: true
  8797. });
  8798. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8799. get: function () {
  8800. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8801. },
  8802. enumerable: true,
  8803. configurable: true
  8804. });
  8805. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8806. get: function () {
  8807. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8808. },
  8809. enumerable: true,
  8810. configurable: true
  8811. });
  8812. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8813. get: function () {
  8814. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8815. },
  8816. enumerable: true,
  8817. configurable: true
  8818. });
  8819. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8820. get: function () {
  8821. return this._bias;
  8822. },
  8823. set: function (bias) {
  8824. this._bias = bias;
  8825. },
  8826. enumerable: true,
  8827. configurable: true
  8828. });
  8829. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8830. get: function () {
  8831. return this._blurBoxOffset;
  8832. },
  8833. set: function (value) {
  8834. var _this = this;
  8835. if (this._blurBoxOffset === value) {
  8836. return;
  8837. }
  8838. this._blurBoxOffset = value;
  8839. if (this._boxBlurPostprocess) {
  8840. this._boxBlurPostprocess.dispose();
  8841. }
  8842. 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);
  8843. this._boxBlurPostprocess.onApply = function (effect) {
  8844. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8845. };
  8846. },
  8847. enumerable: true,
  8848. configurable: true
  8849. });
  8850. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8851. get: function () {
  8852. return this._filter;
  8853. },
  8854. set: function (value) {
  8855. if (this._filter === value) {
  8856. return;
  8857. }
  8858. this._filter = value;
  8859. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8860. this._shadowMap.anisotropicFilteringLevel = 16;
  8861. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8862. }
  8863. else {
  8864. this._shadowMap.anisotropicFilteringLevel = 1;
  8865. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8866. }
  8867. },
  8868. enumerable: true,
  8869. configurable: true
  8870. });
  8871. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8872. get: function () {
  8873. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8874. },
  8875. set: function (value) {
  8876. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8877. },
  8878. enumerable: true,
  8879. configurable: true
  8880. });
  8881. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8882. get: function () {
  8883. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8884. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8885. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8886. },
  8887. set: function (value) {
  8888. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8889. },
  8890. enumerable: true,
  8891. configurable: true
  8892. });
  8893. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8894. get: function () {
  8895. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8896. },
  8897. set: function (value) {
  8898. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8899. },
  8900. enumerable: true,
  8901. configurable: true
  8902. });
  8903. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8904. var defines = [];
  8905. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8906. defines.push("#define VSM");
  8907. }
  8908. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8909. var mesh = subMesh.getMesh();
  8910. var material = subMesh.getMaterial();
  8911. // Alpha test
  8912. if (material && material.needAlphaTesting()) {
  8913. defines.push("#define ALPHATEST");
  8914. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8915. attribs.push(BABYLON.VertexBuffer.UVKind);
  8916. defines.push("#define UV1");
  8917. }
  8918. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8919. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8920. defines.push("#define UV2");
  8921. }
  8922. }
  8923. // Bones
  8924. if (mesh.useBones) {
  8925. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8926. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8927. defines.push("#define BONES");
  8928. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8929. }
  8930. // Instances
  8931. if (useInstances) {
  8932. defines.push("#define INSTANCES");
  8933. attribs.push("world0");
  8934. attribs.push("world1");
  8935. attribs.push("world2");
  8936. attribs.push("world3");
  8937. }
  8938. // Get correct effect
  8939. var join = defines.join("\n");
  8940. if (this._cachedDefines !== join) {
  8941. this._cachedDefines = join;
  8942. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8943. }
  8944. return this._effect.isReady();
  8945. };
  8946. ShadowGenerator.prototype.getShadowMap = function () {
  8947. return this._shadowMap;
  8948. };
  8949. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8950. if (this._shadowMap2) {
  8951. return this._shadowMap2;
  8952. }
  8953. return this._shadowMap;
  8954. };
  8955. ShadowGenerator.prototype.getLight = function () {
  8956. return this._light;
  8957. };
  8958. // Methods
  8959. ShadowGenerator.prototype.getTransformMatrix = function () {
  8960. var scene = this._scene;
  8961. if (this._currentRenderID === scene.getRenderId()) {
  8962. return this._transformMatrix;
  8963. }
  8964. this._currentRenderID = scene.getRenderId();
  8965. var lightPosition = this._light.position;
  8966. var lightDirection = this._light.direction;
  8967. if (this._light.computeTransformedPosition()) {
  8968. lightPosition = this._light.transformedPosition;
  8969. }
  8970. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  8971. this._cachedPosition = lightPosition.clone();
  8972. this._cachedDirection = lightDirection.clone();
  8973. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8974. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8975. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8976. }
  8977. return this._transformMatrix;
  8978. };
  8979. ShadowGenerator.prototype.getDarkness = function () {
  8980. return this._darkness;
  8981. };
  8982. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8983. if (darkness >= 1.0)
  8984. this._darkness = 1.0;
  8985. else if (darkness <= 0.0)
  8986. this._darkness = 0.0;
  8987. else
  8988. this._darkness = darkness;
  8989. };
  8990. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8991. this._transparencyShadow = hasShadow;
  8992. };
  8993. ShadowGenerator.prototype._packHalf = function (depth) {
  8994. var scale = depth * 255.0;
  8995. var fract = scale - Math.floor(scale);
  8996. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8997. };
  8998. ShadowGenerator.prototype.dispose = function () {
  8999. this._shadowMap.dispose();
  9000. if (this._shadowMap2) {
  9001. this._shadowMap2.dispose();
  9002. }
  9003. if (this._downSamplePostprocess) {
  9004. this._downSamplePostprocess.dispose();
  9005. }
  9006. if (this._boxBlurPostprocess) {
  9007. this._boxBlurPostprocess.dispose();
  9008. }
  9009. };
  9010. ShadowGenerator._FILTER_NONE = 0;
  9011. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9012. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9013. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9014. return ShadowGenerator;
  9015. })();
  9016. BABYLON.ShadowGenerator = ShadowGenerator;
  9017. })(BABYLON || (BABYLON = {}));
  9018. //# sourceMappingURL=babylon.shadowGenerator.js.map
  9019. var BABYLON;
  9020. (function (BABYLON) {
  9021. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9022. if (boxMin.x > sphereCenter.x + sphereRadius)
  9023. return false;
  9024. if (sphereCenter.x - sphereRadius > boxMax.x)
  9025. return false;
  9026. if (boxMin.y > sphereCenter.y + sphereRadius)
  9027. return false;
  9028. if (sphereCenter.y - sphereRadius > boxMax.y)
  9029. return false;
  9030. if (boxMin.z > sphereCenter.z + sphereRadius)
  9031. return false;
  9032. if (sphereCenter.z - sphereRadius > boxMax.z)
  9033. return false;
  9034. return true;
  9035. };
  9036. var getLowestRoot = function (a, b, c, maxR) {
  9037. var determinant = b * b - 4.0 * a * c;
  9038. var result = { root: 0, found: false };
  9039. if (determinant < 0)
  9040. return result;
  9041. var sqrtD = Math.sqrt(determinant);
  9042. var r1 = (-b - sqrtD) / (2.0 * a);
  9043. var r2 = (-b + sqrtD) / (2.0 * a);
  9044. if (r1 > r2) {
  9045. var temp = r2;
  9046. r2 = r1;
  9047. r1 = temp;
  9048. }
  9049. if (r1 > 0 && r1 < maxR) {
  9050. result.root = r1;
  9051. result.found = true;
  9052. return result;
  9053. }
  9054. if (r2 > 0 && r2 < maxR) {
  9055. result.root = r2;
  9056. result.found = true;
  9057. return result;
  9058. }
  9059. return result;
  9060. };
  9061. var Collider = (function () {
  9062. function Collider() {
  9063. this.radius = new BABYLON.Vector3(1, 1, 1);
  9064. this.retry = 0;
  9065. this.basePointWorld = BABYLON.Vector3.Zero();
  9066. this.velocityWorld = BABYLON.Vector3.Zero();
  9067. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9068. this._collisionPoint = BABYLON.Vector3.Zero();
  9069. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9070. this._tempVector = BABYLON.Vector3.Zero();
  9071. this._tempVector2 = BABYLON.Vector3.Zero();
  9072. this._tempVector3 = BABYLON.Vector3.Zero();
  9073. this._tempVector4 = BABYLON.Vector3.Zero();
  9074. this._edge = BABYLON.Vector3.Zero();
  9075. this._baseToVertex = BABYLON.Vector3.Zero();
  9076. this._destinationPoint = BABYLON.Vector3.Zero();
  9077. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9078. this._displacementVector = BABYLON.Vector3.Zero();
  9079. }
  9080. // Methods
  9081. Collider.prototype._initialize = function (source, dir, e) {
  9082. this.velocity = dir;
  9083. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9084. this.basePoint = source;
  9085. source.multiplyToRef(this.radius, this.basePointWorld);
  9086. dir.multiplyToRef(this.radius, this.velocityWorld);
  9087. this.velocityWorldLength = this.velocityWorld.length();
  9088. this.epsilon = e;
  9089. this.collisionFound = false;
  9090. };
  9091. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9092. pa.subtractToRef(point, this._tempVector);
  9093. pb.subtractToRef(point, this._tempVector2);
  9094. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9095. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9096. if (d < 0)
  9097. return false;
  9098. pc.subtractToRef(point, this._tempVector3);
  9099. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9100. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9101. if (d < 0)
  9102. return false;
  9103. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9104. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9105. return d >= 0;
  9106. };
  9107. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9108. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9109. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9110. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9111. return false;
  9112. }
  9113. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9114. return false;
  9115. return true;
  9116. };
  9117. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9118. var t0;
  9119. var embeddedInPlane = false;
  9120. //defensive programming, actually not needed.
  9121. if (!trianglePlaneArray) {
  9122. trianglePlaneArray = [];
  9123. }
  9124. if (!trianglePlaneArray[faceIndex]) {
  9125. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9126. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9127. }
  9128. var trianglePlane = trianglePlaneArray[faceIndex];
  9129. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9130. return;
  9131. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9132. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9133. if (normalDotVelocity == 0) {
  9134. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9135. return;
  9136. embeddedInPlane = true;
  9137. t0 = 0;
  9138. }
  9139. else {
  9140. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9141. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9142. if (t0 > t1) {
  9143. var temp = t1;
  9144. t1 = t0;
  9145. t0 = temp;
  9146. }
  9147. if (t0 > 1.0 || t1 < 0.0)
  9148. return;
  9149. if (t0 < 0)
  9150. t0 = 0;
  9151. if (t0 > 1.0)
  9152. t0 = 1.0;
  9153. }
  9154. this._collisionPoint.copyFromFloats(0, 0, 0);
  9155. var found = false;
  9156. var t = 1.0;
  9157. if (!embeddedInPlane) {
  9158. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9159. this.velocity.scaleToRef(t0, this._tempVector);
  9160. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9161. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9162. found = true;
  9163. t = t0;
  9164. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9165. }
  9166. }
  9167. if (!found) {
  9168. var velocitySquaredLength = this.velocity.lengthSquared();
  9169. var a = velocitySquaredLength;
  9170. this.basePoint.subtractToRef(p1, this._tempVector);
  9171. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9172. var c = this._tempVector.lengthSquared() - 1.0;
  9173. var lowestRoot = getLowestRoot(a, b, c, t);
  9174. if (lowestRoot.found) {
  9175. t = lowestRoot.root;
  9176. found = true;
  9177. this._collisionPoint.copyFrom(p1);
  9178. }
  9179. this.basePoint.subtractToRef(p2, this._tempVector);
  9180. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9181. c = this._tempVector.lengthSquared() - 1.0;
  9182. lowestRoot = getLowestRoot(a, b, c, t);
  9183. if (lowestRoot.found) {
  9184. t = lowestRoot.root;
  9185. found = true;
  9186. this._collisionPoint.copyFrom(p2);
  9187. }
  9188. this.basePoint.subtractToRef(p3, this._tempVector);
  9189. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9190. c = this._tempVector.lengthSquared() - 1.0;
  9191. lowestRoot = getLowestRoot(a, b, c, t);
  9192. if (lowestRoot.found) {
  9193. t = lowestRoot.root;
  9194. found = true;
  9195. this._collisionPoint.copyFrom(p3);
  9196. }
  9197. p2.subtractToRef(p1, this._edge);
  9198. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9199. var edgeSquaredLength = this._edge.lengthSquared();
  9200. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9201. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9202. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9203. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9204. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9205. lowestRoot = getLowestRoot(a, b, c, t);
  9206. if (lowestRoot.found) {
  9207. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9208. if (f >= 0.0 && f <= 1.0) {
  9209. t = lowestRoot.root;
  9210. found = true;
  9211. this._edge.scaleInPlace(f);
  9212. p1.addToRef(this._edge, this._collisionPoint);
  9213. }
  9214. }
  9215. p3.subtractToRef(p2, this._edge);
  9216. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9217. edgeSquaredLength = this._edge.lengthSquared();
  9218. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9219. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9220. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9221. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9222. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9223. lowestRoot = getLowestRoot(a, b, c, t);
  9224. if (lowestRoot.found) {
  9225. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9226. if (f >= 0.0 && f <= 1.0) {
  9227. t = lowestRoot.root;
  9228. found = true;
  9229. this._edge.scaleInPlace(f);
  9230. p2.addToRef(this._edge, this._collisionPoint);
  9231. }
  9232. }
  9233. p1.subtractToRef(p3, this._edge);
  9234. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9235. edgeSquaredLength = this._edge.lengthSquared();
  9236. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9237. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9238. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9239. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9240. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9241. lowestRoot = getLowestRoot(a, b, c, t);
  9242. if (lowestRoot.found) {
  9243. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9244. if (f >= 0.0 && f <= 1.0) {
  9245. t = lowestRoot.root;
  9246. found = true;
  9247. this._edge.scaleInPlace(f);
  9248. p3.addToRef(this._edge, this._collisionPoint);
  9249. }
  9250. }
  9251. }
  9252. if (found) {
  9253. var distToCollision = t * this.velocity.length();
  9254. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9255. if (!this.intersectionPoint) {
  9256. this.intersectionPoint = this._collisionPoint.clone();
  9257. }
  9258. else {
  9259. this.intersectionPoint.copyFrom(this._collisionPoint);
  9260. }
  9261. this.nearestDistance = distToCollision;
  9262. this.collisionFound = true;
  9263. }
  9264. }
  9265. };
  9266. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9267. for (var i = indexStart; i < indexEnd; i += 3) {
  9268. var p1 = pts[indices[i] - decal];
  9269. var p2 = pts[indices[i + 1] - decal];
  9270. var p3 = pts[indices[i + 2] - decal];
  9271. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9272. }
  9273. };
  9274. Collider.prototype._getResponse = function (pos, vel) {
  9275. pos.addToRef(vel, this._destinationPoint);
  9276. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9277. this.basePoint.addToRef(vel, pos);
  9278. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9279. this._slidePlaneNormal.normalize();
  9280. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9281. pos.addInPlace(this._displacementVector);
  9282. this.intersectionPoint.addInPlace(this._displacementVector);
  9283. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9284. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9285. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9286. };
  9287. return Collider;
  9288. })();
  9289. BABYLON.Collider = Collider;
  9290. })(BABYLON || (BABYLON = {}));
  9291. //# sourceMappingURL=babylon.collider.js.map
  9292. var BABYLON;
  9293. (function (BABYLON) {
  9294. //WebWorker code will be inserted to this variable.
  9295. BABYLON.CollisionWorker = "";
  9296. (function (WorkerTaskType) {
  9297. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9298. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9299. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9300. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9301. var WorkerTaskType = BABYLON.WorkerTaskType;
  9302. (function (WorkerReplyType) {
  9303. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9304. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9305. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9306. var WorkerReplyType = BABYLON.WorkerReplyType;
  9307. var CollisionCoordinatorWorker = (function () {
  9308. function CollisionCoordinatorWorker() {
  9309. var _this = this;
  9310. this._scaledPosition = BABYLON.Vector3.Zero();
  9311. this._scaledVelocity = BABYLON.Vector3.Zero();
  9312. this.onMeshUpdated = function (mesh) {
  9313. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9314. };
  9315. this.onGeometryUpdated = function (geometry) {
  9316. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9317. };
  9318. this._afterRender = function () {
  9319. if (!_this._init)
  9320. return;
  9321. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9322. return;
  9323. }
  9324. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9325. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9326. if (_this._runningUpdated > 4) {
  9327. return;
  9328. }
  9329. ++_this._runningUpdated;
  9330. var payload = {
  9331. updatedMeshes: _this._addUpdateMeshesList,
  9332. updatedGeometries: _this._addUpdateGeometriesList,
  9333. removedGeometries: _this._toRemoveGeometryArray,
  9334. removedMeshes: _this._toRemoveMeshesArray
  9335. };
  9336. var message = {
  9337. payload: payload,
  9338. taskType: WorkerTaskType.UPDATE
  9339. };
  9340. var serializable = [];
  9341. for (var id in payload.updatedGeometries) {
  9342. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9343. //prepare transferables
  9344. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9345. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9346. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9347. }
  9348. }
  9349. _this._worker.postMessage(message, serializable);
  9350. _this._addUpdateMeshesList = {};
  9351. _this._addUpdateGeometriesList = {};
  9352. _this._toRemoveGeometryArray = [];
  9353. _this._toRemoveMeshesArray = [];
  9354. };
  9355. this._onMessageFromWorker = function (e) {
  9356. var returnData = e.data;
  9357. if (returnData.error != WorkerReplyType.SUCCESS) {
  9358. //TODO what errors can be returned from the worker?
  9359. BABYLON.Tools.Warn("error returned from worker!");
  9360. return;
  9361. }
  9362. switch (returnData.taskType) {
  9363. case WorkerTaskType.INIT:
  9364. _this._init = true;
  9365. //Update the worked with ALL of the scene's current state
  9366. _this._scene.meshes.forEach(function (mesh) {
  9367. _this.onMeshAdded(mesh);
  9368. });
  9369. _this._scene.getGeometries().forEach(function (geometry) {
  9370. _this.onGeometryAdded(geometry);
  9371. });
  9372. break;
  9373. case WorkerTaskType.UPDATE:
  9374. _this._runningUpdated--;
  9375. break;
  9376. case WorkerTaskType.COLLIDE:
  9377. _this._runningCollisionTask = false;
  9378. var returnPayload = returnData.payload;
  9379. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9380. return;
  9381. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9382. //cleanup
  9383. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9384. break;
  9385. }
  9386. };
  9387. this._collisionsCallbackArray = [];
  9388. this._init = false;
  9389. this._runningUpdated = 0;
  9390. this._runningCollisionTask = false;
  9391. this._addUpdateMeshesList = {};
  9392. this._addUpdateGeometriesList = {};
  9393. this._toRemoveGeometryArray = [];
  9394. this._toRemoveMeshesArray = [];
  9395. }
  9396. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9397. if (!this._init)
  9398. return;
  9399. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9400. return;
  9401. position.divideToRef(collider.radius, this._scaledPosition);
  9402. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9403. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9404. var payload = {
  9405. collider: {
  9406. position: this._scaledPosition.asArray(),
  9407. velocity: this._scaledVelocity.asArray(),
  9408. radius: collider.radius.asArray()
  9409. },
  9410. collisionId: collisionIndex,
  9411. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9412. maximumRetry: maximumRetry
  9413. };
  9414. var message = {
  9415. payload: payload,
  9416. taskType: WorkerTaskType.COLLIDE
  9417. };
  9418. this._worker.postMessage(message);
  9419. };
  9420. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9421. this._scene = scene;
  9422. this._scene.registerAfterRender(this._afterRender);
  9423. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9424. this._worker = new Worker(workerUrl);
  9425. this._worker.onmessage = this._onMessageFromWorker;
  9426. var message = {
  9427. payload: {},
  9428. taskType: WorkerTaskType.INIT
  9429. };
  9430. this._worker.postMessage(message);
  9431. };
  9432. CollisionCoordinatorWorker.prototype.destroy = function () {
  9433. this._scene.unregisterAfterRender(this._afterRender);
  9434. this._worker.terminate();
  9435. };
  9436. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9437. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9438. this.onMeshUpdated(mesh);
  9439. };
  9440. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9441. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9442. };
  9443. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9444. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9445. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9446. this.onGeometryUpdated(geometry);
  9447. };
  9448. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9449. this._toRemoveGeometryArray.push(geometry.id);
  9450. };
  9451. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9452. var submeshes = [];
  9453. if (mesh.subMeshes) {
  9454. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9455. return {
  9456. position: idx,
  9457. verticesStart: sm.verticesStart,
  9458. verticesCount: sm.verticesCount,
  9459. indexStart: sm.indexStart,
  9460. indexCount: sm.indexCount,
  9461. hasMaterial: !!sm.getMaterial(),
  9462. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9463. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9464. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9465. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9466. };
  9467. });
  9468. }
  9469. var geometryId = mesh.geometry ? mesh.geometry.id : null;
  9470. return {
  9471. uniqueId: mesh.uniqueId,
  9472. id: mesh.id,
  9473. name: mesh.name,
  9474. geometryId: geometryId,
  9475. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9476. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9477. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9478. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9479. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9480. subMeshes: submeshes,
  9481. checkCollisions: mesh.checkCollisions
  9482. };
  9483. };
  9484. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9485. return {
  9486. id: geometry.id,
  9487. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9488. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9489. indices: new Int32Array(geometry.getIndices() || []),
  9490. };
  9491. };
  9492. return CollisionCoordinatorWorker;
  9493. })();
  9494. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9495. var CollisionCoordinatorLegacy = (function () {
  9496. function CollisionCoordinatorLegacy() {
  9497. this._scaledPosition = BABYLON.Vector3.Zero();
  9498. this._scaledVelocity = BABYLON.Vector3.Zero();
  9499. this._finalPosition = BABYLON.Vector3.Zero();
  9500. }
  9501. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9502. position.divideToRef(collider.radius, this._scaledPosition);
  9503. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9504. collider.retry = 0;
  9505. collider.initialVelocity = this._scaledVelocity;
  9506. collider.initialPosition = this._scaledPosition;
  9507. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9508. this._finalPosition.multiplyInPlace(collider.radius);
  9509. //run the callback
  9510. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9511. };
  9512. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9513. this._scene = scene;
  9514. };
  9515. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9516. //Legacy need no destruction method.
  9517. };
  9518. //No update in legacy mode
  9519. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9520. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9521. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9522. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9523. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9524. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9525. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9526. if (excludedMesh === void 0) { excludedMesh = null; }
  9527. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9528. if (collider.retry >= maximumRetry) {
  9529. finalPosition.copyFrom(position);
  9530. return;
  9531. }
  9532. collider._initialize(position, velocity, closeDistance);
  9533. // Check all meshes
  9534. for (var index = 0; index < this._scene.meshes.length; index++) {
  9535. var mesh = this._scene.meshes[index];
  9536. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9537. mesh._checkCollision(collider);
  9538. }
  9539. }
  9540. if (!collider.collisionFound) {
  9541. position.addToRef(velocity, finalPosition);
  9542. return;
  9543. }
  9544. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9545. collider._getResponse(position, velocity);
  9546. }
  9547. if (velocity.length() <= closeDistance) {
  9548. finalPosition.copyFrom(position);
  9549. return;
  9550. }
  9551. collider.retry++;
  9552. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9553. };
  9554. return CollisionCoordinatorLegacy;
  9555. })();
  9556. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9557. })(BABYLON || (BABYLON = {}));
  9558. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  9559. var __extends = this.__extends || function (d, b) {
  9560. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9561. function __() { this.constructor = d; }
  9562. __.prototype = b.prototype;
  9563. d.prototype = new __();
  9564. };
  9565. var BABYLON;
  9566. (function (BABYLON) {
  9567. var VRCameraMetrics = (function () {
  9568. function VRCameraMetrics() {
  9569. this.compensateDistorsion = true;
  9570. }
  9571. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9572. get: function () {
  9573. return this.hResolution / (2 * this.vResolution);
  9574. },
  9575. enumerable: true,
  9576. configurable: true
  9577. });
  9578. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9579. get: function () {
  9580. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9581. },
  9582. enumerable: true,
  9583. configurable: true
  9584. });
  9585. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9586. get: function () {
  9587. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9588. var h = (4 * meters) / this.hScreenSize;
  9589. return BABYLON.Matrix.Translation(h, 0, 0);
  9590. },
  9591. enumerable: true,
  9592. configurable: true
  9593. });
  9594. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9595. get: function () {
  9596. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9597. var h = (4 * meters) / this.hScreenSize;
  9598. return BABYLON.Matrix.Translation(-h, 0, 0);
  9599. },
  9600. enumerable: true,
  9601. configurable: true
  9602. });
  9603. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9604. get: function () {
  9605. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9606. },
  9607. enumerable: true,
  9608. configurable: true
  9609. });
  9610. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9611. get: function () {
  9612. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9613. },
  9614. enumerable: true,
  9615. configurable: true
  9616. });
  9617. VRCameraMetrics.GetDefault = function () {
  9618. var result = new VRCameraMetrics();
  9619. result.hResolution = 1280;
  9620. result.vResolution = 800;
  9621. result.hScreenSize = 0.149759993;
  9622. result.vScreenSize = 0.0935999975;
  9623. result.vScreenCenter = 0.0467999987,
  9624. result.eyeToScreenDistance = 0.0410000011;
  9625. result.lensSeparationDistance = 0.0635000020;
  9626. result.interpupillaryDistance = 0.0640000030;
  9627. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9628. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9629. result.postProcessScaleFactor = 1.714605507808412;
  9630. result.lensCenterOffset = 0.151976421;
  9631. return result;
  9632. };
  9633. return VRCameraMetrics;
  9634. })();
  9635. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9636. var Camera = (function (_super) {
  9637. __extends(Camera, _super);
  9638. function Camera(name, position, scene) {
  9639. _super.call(this, name, scene);
  9640. this.position = position;
  9641. // Members
  9642. this.upVector = BABYLON.Vector3.Up();
  9643. this.orthoLeft = null;
  9644. this.orthoRight = null;
  9645. this.orthoBottom = null;
  9646. this.orthoTop = null;
  9647. this.fov = 0.8;
  9648. this.minZ = 1.0;
  9649. this.maxZ = 10000.0;
  9650. this.inertia = 0.9;
  9651. this.mode = Camera.PERSPECTIVE_CAMERA;
  9652. this.isIntermediate = false;
  9653. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9654. this.layerMask = 0x0FFFFFFF;
  9655. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9656. // Subcamera members
  9657. this.subCameras = new Array();
  9658. this._subCameraMode = Camera.SUB_CAMERA_MODE_NONE;
  9659. // Cache
  9660. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9661. this._projectionMatrix = new BABYLON.Matrix();
  9662. this._postProcesses = new Array();
  9663. this._postProcessesTakenIndices = [];
  9664. this._activeMeshes = new BABYLON.SmartArray(256);
  9665. this._globalPosition = BABYLON.Vector3.Zero();
  9666. scene.addCamera(this);
  9667. if (!scene.activeCamera) {
  9668. scene.activeCamera = this;
  9669. }
  9670. }
  9671. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9672. get: function () {
  9673. return Camera._PERSPECTIVE_CAMERA;
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9679. get: function () {
  9680. return Camera._ORTHOGRAPHIC_CAMERA;
  9681. },
  9682. enumerable: true,
  9683. configurable: true
  9684. });
  9685. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9686. get: function () {
  9687. return Camera._FOVMODE_VERTICAL_FIXED;
  9688. },
  9689. enumerable: true,
  9690. configurable: true
  9691. });
  9692. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9693. get: function () {
  9694. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9695. },
  9696. enumerable: true,
  9697. configurable: true
  9698. });
  9699. Object.defineProperty(Camera, "SUB_CAMERA_MODE_NONE", {
  9700. get: function () {
  9701. return Camera._SUB_CAMERA_MODE_NONE;
  9702. },
  9703. enumerable: true,
  9704. configurable: true
  9705. });
  9706. Object.defineProperty(Camera, "SUB_CAMERA_MODE_ANAGLYPH", {
  9707. get: function () {
  9708. return Camera._SUB_CAMERA_MODE_ANAGLYPH;
  9709. },
  9710. enumerable: true,
  9711. configurable: true
  9712. });
  9713. Object.defineProperty(Camera, "SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM", {
  9714. get: function () {
  9715. return Camera._SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Object.defineProperty(Camera, "SUB_CAMERA_MODE_VERTICAL_STEREOGRAM", {
  9721. get: function () {
  9722. return Camera._SUB_CAMERA_MODE_VERTICAL_STEREOGRAM;
  9723. },
  9724. enumerable: true,
  9725. configurable: true
  9726. });
  9727. Object.defineProperty(Camera, "SUB_CAMERA_MODE_VR", {
  9728. get: function () {
  9729. return Camera._SUB_CAMERA_MODE_VR;
  9730. },
  9731. enumerable: true,
  9732. configurable: true
  9733. });
  9734. Object.defineProperty(Camera, "SUB_CAMERAID_A", {
  9735. get: function () {
  9736. return Camera._SUB_CAMERAID_A;
  9737. },
  9738. enumerable: true,
  9739. configurable: true
  9740. });
  9741. Object.defineProperty(Camera, "SUB_CAMERAID_B", {
  9742. get: function () {
  9743. return Camera._SUB_CAMERAID_B;
  9744. },
  9745. enumerable: true,
  9746. configurable: true
  9747. });
  9748. Object.defineProperty(Camera.prototype, "globalPosition", {
  9749. get: function () {
  9750. return this._globalPosition;
  9751. },
  9752. enumerable: true,
  9753. configurable: true
  9754. });
  9755. Camera.prototype.getActiveMeshes = function () {
  9756. return this._activeMeshes;
  9757. };
  9758. Camera.prototype.isActiveMesh = function (mesh) {
  9759. return (this._activeMeshes.indexOf(mesh) !== -1);
  9760. };
  9761. //Cache
  9762. Camera.prototype._initCache = function () {
  9763. _super.prototype._initCache.call(this);
  9764. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9765. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9766. this._cache.mode = undefined;
  9767. this._cache.minZ = undefined;
  9768. this._cache.maxZ = undefined;
  9769. this._cache.fov = undefined;
  9770. this._cache.aspectRatio = undefined;
  9771. this._cache.orthoLeft = undefined;
  9772. this._cache.orthoRight = undefined;
  9773. this._cache.orthoBottom = undefined;
  9774. this._cache.orthoTop = undefined;
  9775. this._cache.renderWidth = undefined;
  9776. this._cache.renderHeight = undefined;
  9777. };
  9778. Camera.prototype._updateCache = function (ignoreParentClass) {
  9779. if (!ignoreParentClass) {
  9780. _super.prototype._updateCache.call(this);
  9781. }
  9782. var engine = this.getEngine();
  9783. this._cache.position.copyFrom(this.position);
  9784. this._cache.upVector.copyFrom(this.upVector);
  9785. this._cache.mode = this.mode;
  9786. this._cache.minZ = this.minZ;
  9787. this._cache.maxZ = this.maxZ;
  9788. this._cache.fov = this.fov;
  9789. this._cache.aspectRatio = engine.getAspectRatio(this);
  9790. this._cache.orthoLeft = this.orthoLeft;
  9791. this._cache.orthoRight = this.orthoRight;
  9792. this._cache.orthoBottom = this.orthoBottom;
  9793. this._cache.orthoTop = this.orthoTop;
  9794. this._cache.renderWidth = engine.getRenderWidth();
  9795. this._cache.renderHeight = engine.getRenderHeight();
  9796. };
  9797. Camera.prototype._updateFromScene = function () {
  9798. this.updateCache();
  9799. this._update();
  9800. };
  9801. // Synchronized
  9802. Camera.prototype._isSynchronized = function () {
  9803. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9804. };
  9805. Camera.prototype._isSynchronizedViewMatrix = function () {
  9806. if (!_super.prototype._isSynchronized.call(this))
  9807. return false;
  9808. return this._cache.position.equals(this.position)
  9809. && this._cache.upVector.equals(this.upVector)
  9810. && this.isSynchronizedWithParent();
  9811. };
  9812. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9813. var check = this._cache.mode === this.mode
  9814. && this._cache.minZ === this.minZ
  9815. && this._cache.maxZ === this.maxZ;
  9816. if (!check) {
  9817. return false;
  9818. }
  9819. var engine = this.getEngine();
  9820. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9821. check = this._cache.fov === this.fov
  9822. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9823. }
  9824. else {
  9825. check = this._cache.orthoLeft === this.orthoLeft
  9826. && this._cache.orthoRight === this.orthoRight
  9827. && this._cache.orthoBottom === this.orthoBottom
  9828. && this._cache.orthoTop === this.orthoTop
  9829. && this._cache.renderWidth === engine.getRenderWidth()
  9830. && this._cache.renderHeight === engine.getRenderHeight();
  9831. }
  9832. return check;
  9833. };
  9834. // Controls
  9835. Camera.prototype.attachControl = function (element) {
  9836. };
  9837. Camera.prototype.detachControl = function (element) {
  9838. };
  9839. Camera.prototype._update = function () {
  9840. this._checkInputs();
  9841. if (this._subCameraMode !== Camera.SUB_CAMERA_MODE_NONE) {
  9842. this._updateSubCameras();
  9843. }
  9844. };
  9845. Camera.prototype._checkInputs = function () {
  9846. };
  9847. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9848. if (insertAt === void 0) { insertAt = null; }
  9849. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9850. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9851. return 0;
  9852. }
  9853. if (insertAt == null || insertAt < 0) {
  9854. this._postProcesses.push(postProcess);
  9855. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9856. return this._postProcesses.length - 1;
  9857. }
  9858. var add = 0;
  9859. if (this._postProcesses[insertAt]) {
  9860. var start = this._postProcesses.length - 1;
  9861. for (var i = start; i >= insertAt + 1; --i) {
  9862. this._postProcesses[i + 1] = this._postProcesses[i];
  9863. }
  9864. add = 1;
  9865. }
  9866. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9867. if (this._postProcessesTakenIndices[i] < insertAt) {
  9868. continue;
  9869. }
  9870. start = this._postProcessesTakenIndices.length - 1;
  9871. for (var j = start; j >= i; --j) {
  9872. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9873. }
  9874. this._postProcessesTakenIndices[i] = insertAt;
  9875. break;
  9876. }
  9877. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  9878. this._postProcessesTakenIndices.push(insertAt);
  9879. }
  9880. var result = insertAt + add;
  9881. this._postProcesses[result] = postProcess;
  9882. return result;
  9883. };
  9884. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9885. if (atIndices === void 0) { atIndices = null; }
  9886. var result = [];
  9887. if (!atIndices) {
  9888. var length = this._postProcesses.length;
  9889. for (var i = 0; i < length; i++) {
  9890. if (this._postProcesses[i] !== postProcess) {
  9891. continue;
  9892. }
  9893. delete this._postProcesses[i];
  9894. var index = this._postProcessesTakenIndices.indexOf(i);
  9895. this._postProcessesTakenIndices.splice(index, 1);
  9896. }
  9897. }
  9898. else {
  9899. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9900. for (i = 0; i < atIndices.length; i++) {
  9901. var foundPostProcess = this._postProcesses[atIndices[i]];
  9902. if (foundPostProcess !== postProcess) {
  9903. result.push(i);
  9904. continue;
  9905. }
  9906. delete this._postProcesses[atIndices[i]];
  9907. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9908. this._postProcessesTakenIndices.splice(index, 1);
  9909. }
  9910. }
  9911. return result;
  9912. };
  9913. Camera.prototype.getWorldMatrix = function () {
  9914. if (!this._worldMatrix) {
  9915. this._worldMatrix = BABYLON.Matrix.Identity();
  9916. }
  9917. var viewMatrix = this.getViewMatrix();
  9918. viewMatrix.invertToRef(this._worldMatrix);
  9919. return this._worldMatrix;
  9920. };
  9921. Camera.prototype._getViewMatrix = function () {
  9922. return BABYLON.Matrix.Identity();
  9923. };
  9924. Camera.prototype.getViewMatrix = function (force) {
  9925. this._computedViewMatrix = this._computeViewMatrix(force);
  9926. if (!force && this._isSynchronizedViewMatrix()) {
  9927. return this._computedViewMatrix;
  9928. }
  9929. if (!this.parent || !this.parent.getWorldMatrix) {
  9930. this._globalPosition.copyFrom(this.position);
  9931. }
  9932. else {
  9933. if (!this._worldMatrix) {
  9934. this._worldMatrix = BABYLON.Matrix.Identity();
  9935. }
  9936. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9937. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9938. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9939. this._computedViewMatrix.invert();
  9940. this._markSyncedWithParent();
  9941. }
  9942. this._currentRenderId = this.getScene().getRenderId();
  9943. return this._computedViewMatrix;
  9944. };
  9945. Camera.prototype._computeViewMatrix = function (force) {
  9946. if (!force && this._isSynchronizedViewMatrix()) {
  9947. return this._computedViewMatrix;
  9948. }
  9949. this._computedViewMatrix = this._getViewMatrix();
  9950. this._currentRenderId = this.getScene().getRenderId();
  9951. return this._computedViewMatrix;
  9952. };
  9953. Camera.prototype.getProjectionMatrix = function (force) {
  9954. if (!force && this._isSynchronizedProjectionMatrix()) {
  9955. return this._projectionMatrix;
  9956. }
  9957. var engine = this.getEngine();
  9958. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9959. if (this.minZ <= 0) {
  9960. this.minZ = 0.1;
  9961. }
  9962. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9963. return this._projectionMatrix;
  9964. }
  9965. var halfWidth = engine.getRenderWidth() / 2.0;
  9966. var halfHeight = engine.getRenderHeight() / 2.0;
  9967. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9968. return this._projectionMatrix;
  9969. };
  9970. Camera.prototype.dispose = function () {
  9971. // Remove from scene
  9972. this.getScene().removeCamera(this);
  9973. while (this.subCameras.length > 0) {
  9974. this.subCameras.pop().dispose();
  9975. }
  9976. // Postprocesses
  9977. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9978. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9979. }
  9980. };
  9981. // ---- 3D cameras section ----
  9982. Camera.prototype.setSubCameraMode = function (mode, halfSpace, metrics) {
  9983. if (halfSpace === void 0) { halfSpace = 0; }
  9984. while (this.subCameras.length > 0) {
  9985. this.subCameras.pop().dispose();
  9986. }
  9987. this._subCameraMode = mode;
  9988. this._subCamHalfSpace = BABYLON.Tools.ToRadians(halfSpace);
  9989. var camA = this.getSubCamera(this.name + "_A", true);
  9990. var camB = this.getSubCamera(this.name + "_B", false);
  9991. var postProcessA;
  9992. var postProcessB;
  9993. switch (this._subCameraMode) {
  9994. case Camera.SUB_CAMERA_MODE_ANAGLYPH:
  9995. postProcessA = new BABYLON.PassPostProcess(this.name + "_leftTexture", 1.0, camA);
  9996. camA.isIntermediate = true;
  9997. postProcessB = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, camB);
  9998. postProcessB.onApply = function (effect) {
  9999. effect.setTextureFromPostProcess("leftSampler", postProcessA);
  10000. };
  10001. break;
  10002. case Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM:
  10003. case Camera.SUB_CAMERA_MODE_VERTICAL_STEREOGRAM:
  10004. var isStereogramHoriz = this._subCameraMode === Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM;
  10005. postProcessA = new BABYLON.PassPostProcess("passthru", 1.0, camA);
  10006. camA.isIntermediate = true;
  10007. postProcessB = new BABYLON.StereogramInterlacePostProcess("st_interlace", camB, postProcessA, isStereogramHoriz);
  10008. break;
  10009. case Camera.SUB_CAMERA_MODE_VR:
  10010. metrics = metrics || VRCameraMetrics.GetDefault();
  10011. camA._vrMetrics = metrics;
  10012. camA.viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10013. camA._vrWorkMatrix = new BABYLON.Matrix();
  10014. camA._vrHMatrix = metrics.leftHMatrix;
  10015. camA._vrPreViewMatrix = metrics.leftPreViewMatrix;
  10016. camA.getProjectionMatrix = camA._getVRProjectionMatrix;
  10017. if (metrics.compensateDistorsion) {
  10018. postProcessA = new BABYLON.VRDistortionCorrectionPostProcess("Distortion Compensation Left", camA, false, metrics);
  10019. }
  10020. camB._vrMetrics = camA._vrMetrics;
  10021. camB.viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10022. camB._vrWorkMatrix = new BABYLON.Matrix();
  10023. camB._vrHMatrix = metrics.rightHMatrix;
  10024. camB._vrPreViewMatrix = metrics.rightPreViewMatrix;
  10025. camB.getProjectionMatrix = camB._getVRProjectionMatrix;
  10026. if (metrics.compensateDistorsion) {
  10027. postProcessB = new BABYLON.VRDistortionCorrectionPostProcess("Distortion Compensation Right", camB, true, metrics);
  10028. }
  10029. }
  10030. if (this._subCameraMode !== Camera.SUB_CAMERA_MODE_NONE) {
  10031. this.subCameras.push(camA);
  10032. this.subCameras.push(camB);
  10033. }
  10034. this._update();
  10035. };
  10036. Camera.prototype._getVRProjectionMatrix = function () {
  10037. BABYLON.Matrix.PerspectiveFovLHToRef(this._vrMetrics.aspectRatioFov, this._vrMetrics.aspectRatio, this.minZ, this.maxZ, this._vrWorkMatrix);
  10038. this._vrWorkMatrix.multiplyToRef(this._vrHMatrix, this._projectionMatrix);
  10039. return this._projectionMatrix;
  10040. };
  10041. Camera.prototype.setSubCamHalfSpace = function (halfSpace) {
  10042. this._subCamHalfSpace = BABYLON.Tools.ToRadians(halfSpace);
  10043. };
  10044. /**
  10045. * May needs to be overridden by children so sub has required properties to be copied
  10046. */
  10047. Camera.prototype.getSubCamera = function (name, isA) {
  10048. return null;
  10049. };
  10050. /**
  10051. * May needs to be overridden by children
  10052. */
  10053. Camera.prototype._updateSubCameras = function () {
  10054. var camA = this.subCameras[Camera.SUB_CAMERAID_A];
  10055. var camB = this.subCameras[Camera.SUB_CAMERAID_B];
  10056. camA.minZ = camB.minZ = this.minZ;
  10057. camA.maxZ = camB.maxZ = this.maxZ;
  10058. camA.fov = camB.fov = this.fov;
  10059. // only update viewport, when ANAGLYPH
  10060. if (this._subCameraMode === Camera.SUB_CAMERA_MODE_ANAGLYPH) {
  10061. camA.viewport = camB.viewport = this.viewport;
  10062. }
  10063. };
  10064. // Statics
  10065. Camera._PERSPECTIVE_CAMERA = 0;
  10066. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10067. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10068. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10069. Camera._SUB_CAMERA_MODE_NONE = 0;
  10070. Camera._SUB_CAMERA_MODE_ANAGLYPH = 1;
  10071. Camera._SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM = 2;
  10072. Camera._SUB_CAMERA_MODE_VERTICAL_STEREOGRAM = 3;
  10073. Camera._SUB_CAMERA_MODE_VR = 4;
  10074. Camera._SUB_CAMERAID_A = 0;
  10075. Camera._SUB_CAMERAID_B = 1;
  10076. return Camera;
  10077. })(BABYLON.Node);
  10078. BABYLON.Camera = Camera;
  10079. })(BABYLON || (BABYLON = {}));
  10080. //# sourceMappingURL=babylon.camera.js.map
  10081. var __extends = this.__extends || function (d, b) {
  10082. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10083. function __() { this.constructor = d; }
  10084. __.prototype = b.prototype;
  10085. d.prototype = new __();
  10086. };
  10087. var BABYLON;
  10088. (function (BABYLON) {
  10089. var TargetCamera = (function (_super) {
  10090. __extends(TargetCamera, _super);
  10091. function TargetCamera(name, position, scene) {
  10092. _super.call(this, name, position, scene);
  10093. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10094. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10095. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10096. this.speed = 2.0;
  10097. this.noRotationConstraint = false;
  10098. this.lockedTarget = null;
  10099. this._currentTarget = BABYLON.Vector3.Zero();
  10100. this._viewMatrix = BABYLON.Matrix.Zero();
  10101. this._camMatrix = BABYLON.Matrix.Zero();
  10102. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10103. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10104. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10105. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10106. this._lookAtTemp = BABYLON.Matrix.Zero();
  10107. this._tempMatrix = BABYLON.Matrix.Zero();
  10108. }
  10109. TargetCamera.prototype._getLockedTargetPosition = function () {
  10110. if (!this.lockedTarget) {
  10111. return null;
  10112. }
  10113. return this.lockedTarget.position || this.lockedTarget;
  10114. };
  10115. // Cache
  10116. TargetCamera.prototype._initCache = function () {
  10117. _super.prototype._initCache.call(this);
  10118. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10119. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10120. };
  10121. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10122. if (!ignoreParentClass) {
  10123. _super.prototype._updateCache.call(this);
  10124. }
  10125. var lockedTargetPosition = this._getLockedTargetPosition();
  10126. if (!lockedTargetPosition) {
  10127. this._cache.lockedTarget = null;
  10128. }
  10129. else {
  10130. if (!this._cache.lockedTarget) {
  10131. this._cache.lockedTarget = lockedTargetPosition.clone();
  10132. }
  10133. else {
  10134. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10135. }
  10136. }
  10137. this._cache.rotation.copyFrom(this.rotation);
  10138. };
  10139. // Synchronized
  10140. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10141. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10142. return false;
  10143. }
  10144. var lockedTargetPosition = this._getLockedTargetPosition();
  10145. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10146. && this._cache.rotation.equals(this.rotation);
  10147. };
  10148. // Methods
  10149. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10150. var engine = this.getEngine();
  10151. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10152. };
  10153. // Target
  10154. TargetCamera.prototype.setTarget = function (target) {
  10155. this.upVector.normalize();
  10156. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10157. this._camMatrix.invert();
  10158. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10159. var vDir = target.subtract(this.position);
  10160. if (vDir.x >= 0.0) {
  10161. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10162. }
  10163. else {
  10164. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10165. }
  10166. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10167. if (isNaN(this.rotation.x)) {
  10168. this.rotation.x = 0;
  10169. }
  10170. if (isNaN(this.rotation.y)) {
  10171. this.rotation.y = 0;
  10172. }
  10173. if (isNaN(this.rotation.z)) {
  10174. this.rotation.z = 0;
  10175. }
  10176. };
  10177. TargetCamera.prototype.getTarget = function () {
  10178. return this._currentTarget;
  10179. };
  10180. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10181. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10182. };
  10183. TargetCamera.prototype._updatePosition = function () {
  10184. this.position.addInPlace(this.cameraDirection);
  10185. };
  10186. TargetCamera.prototype._checkInputs = function () {
  10187. var needToMove = this._decideIfNeedsToMove();
  10188. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10189. // Move
  10190. if (needToMove) {
  10191. this._updatePosition();
  10192. }
  10193. // Rotate
  10194. if (needToRotate) {
  10195. this.rotation.x += this.cameraRotation.x;
  10196. this.rotation.y += this.cameraRotation.y;
  10197. if (!this.noRotationConstraint) {
  10198. var limit = (Math.PI / 2) * 0.95;
  10199. if (this.rotation.x > limit)
  10200. this.rotation.x = limit;
  10201. if (this.rotation.x < -limit)
  10202. this.rotation.x = -limit;
  10203. }
  10204. }
  10205. // Inertia
  10206. if (needToMove) {
  10207. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10208. this.cameraDirection.x = 0;
  10209. }
  10210. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10211. this.cameraDirection.y = 0;
  10212. }
  10213. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10214. this.cameraDirection.z = 0;
  10215. }
  10216. this.cameraDirection.scaleInPlace(this.inertia);
  10217. }
  10218. if (needToRotate) {
  10219. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10220. this.cameraRotation.x = 0;
  10221. }
  10222. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10223. this.cameraRotation.y = 0;
  10224. }
  10225. this.cameraRotation.scaleInPlace(this.inertia);
  10226. }
  10227. _super.prototype._checkInputs.call(this);
  10228. };
  10229. TargetCamera.prototype._getViewMatrix = function () {
  10230. if (!this.lockedTarget) {
  10231. // Compute
  10232. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10233. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10234. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10235. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10236. this._lookAtTemp.invert();
  10237. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10238. }
  10239. else {
  10240. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10241. }
  10242. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10243. // Computing target and final matrix
  10244. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10245. }
  10246. else {
  10247. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10248. }
  10249. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10250. return this._viewMatrix;
  10251. };
  10252. TargetCamera.prototype._getVRViewMatrix = function () {
  10253. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10254. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10255. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._vrActualUp);
  10256. // Computing target and final matrix
  10257. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10258. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._vrActualUp, this._vrWorkMatrix);
  10259. this._vrWorkMatrix.multiplyToRef(this._vrPreViewMatrix, this._viewMatrix);
  10260. return this._viewMatrix;
  10261. };
  10262. /**
  10263. * @override
  10264. * needs to be overridden, so sub has required properties to be copied
  10265. */
  10266. TargetCamera.prototype.getSubCamera = function (name, isA) {
  10267. var subCamera = new BABYLON.TargetCamera(name, this.position.clone(), this.getScene());
  10268. if (this._subCameraMode === BABYLON.Camera.SUB_CAMERA_MODE_VR) {
  10269. subCamera._vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10270. subCamera._getViewMatrix = subCamera._getVRViewMatrix;
  10271. }
  10272. return subCamera;
  10273. };
  10274. /**
  10275. * @override
  10276. * needs to be overridden, adding copy of position, and rotation for VR, or target for rest
  10277. */
  10278. TargetCamera.prototype._updateSubCameras = function () {
  10279. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  10280. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  10281. if (this._subCameraMode === BABYLON.Camera.SUB_CAMERA_MODE_VR) {
  10282. camA.rotation.x = camB.rotation.x = this.rotation.x;
  10283. camA.rotation.y = camB.rotation.y = this.rotation.y;
  10284. camA.rotation.z = camB.rotation.z = this.rotation.z;
  10285. camA.position.copyFrom(this.position);
  10286. camB.position.copyFrom(this.position);
  10287. }
  10288. else {
  10289. camA.setTarget(this.getTarget());
  10290. camB.setTarget(this.getTarget());
  10291. this._getSubCamPosition(-this._subCamHalfSpace, camA.position);
  10292. this._getSubCamPosition(this._subCamHalfSpace, camB.position);
  10293. }
  10294. _super.prototype._updateSubCameras.call(this);
  10295. };
  10296. TargetCamera.prototype._getSubCamPosition = function (halfSpace, result) {
  10297. if (!this._subCamTransformMatrix) {
  10298. this._subCamTransformMatrix = new BABYLON.Matrix();
  10299. }
  10300. var target = this.getTarget();
  10301. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._subCamTransformMatrix);
  10302. this._subCamTransformMatrix = this._subCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10303. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._subCamTransformMatrix, result);
  10304. };
  10305. return TargetCamera;
  10306. })(BABYLON.Camera);
  10307. BABYLON.TargetCamera = TargetCamera;
  10308. })(BABYLON || (BABYLON = {}));
  10309. //# sourceMappingURL=babylon.targetCamera.js.map
  10310. var __extends = this.__extends || function (d, b) {
  10311. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10312. function __() { this.constructor = d; }
  10313. __.prototype = b.prototype;
  10314. d.prototype = new __();
  10315. };
  10316. var BABYLON;
  10317. (function (BABYLON) {
  10318. var FreeCamera = (function (_super) {
  10319. __extends(FreeCamera, _super);
  10320. function FreeCamera(name, position, scene) {
  10321. var _this = this;
  10322. _super.call(this, name, position, scene);
  10323. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10324. this.keysUp = [38];
  10325. this.keysDown = [40];
  10326. this.keysLeft = [37];
  10327. this.keysRight = [39];
  10328. this.checkCollisions = false;
  10329. this.applyGravity = false;
  10330. this.angularSensibility = 2000.0;
  10331. this._keys = [];
  10332. this._collider = new BABYLON.Collider();
  10333. this._needMoveForGravity = false;
  10334. this._oldPosition = BABYLON.Vector3.Zero();
  10335. this._diffPosition = BABYLON.Vector3.Zero();
  10336. this._newPosition = BABYLON.Vector3.Zero();
  10337. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10338. if (collidedMesh === void 0) { collidedMesh = null; }
  10339. //TODO move this to the collision coordinator!
  10340. if (_this.getScene().workerCollisions)
  10341. newPosition.multiplyInPlace(_this._collider.radius);
  10342. var updatePosition = function (newPos) {
  10343. _this._newPosition.copyFrom(newPos);
  10344. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10345. var oldPosition = _this.position.clone();
  10346. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10347. _this.position.addInPlace(_this._diffPosition);
  10348. if (_this.onCollide && collidedMesh) {
  10349. _this.onCollide(collidedMesh);
  10350. }
  10351. }
  10352. };
  10353. updatePosition(newPosition);
  10354. };
  10355. }
  10356. // Controls
  10357. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10358. var _this = this;
  10359. var previousPosition;
  10360. var engine = this.getEngine();
  10361. if (this._attachedElement) {
  10362. return;
  10363. }
  10364. this._attachedElement = element;
  10365. if (this._onMouseDown === undefined) {
  10366. this._onMouseDown = function (evt) {
  10367. previousPosition = {
  10368. x: evt.clientX,
  10369. y: evt.clientY
  10370. };
  10371. if (!noPreventDefault) {
  10372. evt.preventDefault();
  10373. }
  10374. };
  10375. this._onMouseUp = function (evt) {
  10376. previousPosition = null;
  10377. if (!noPreventDefault) {
  10378. evt.preventDefault();
  10379. }
  10380. };
  10381. this._onMouseOut = function (evt) {
  10382. previousPosition = null;
  10383. _this._keys = [];
  10384. if (!noPreventDefault) {
  10385. evt.preventDefault();
  10386. }
  10387. };
  10388. this._onMouseMove = function (evt) {
  10389. if (!previousPosition && !engine.isPointerLock) {
  10390. return;
  10391. }
  10392. var offsetX;
  10393. var offsetY;
  10394. if (!engine.isPointerLock) {
  10395. offsetX = evt.clientX - previousPosition.x;
  10396. offsetY = evt.clientY - previousPosition.y;
  10397. }
  10398. else {
  10399. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10400. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10401. }
  10402. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10403. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10404. previousPosition = {
  10405. x: evt.clientX,
  10406. y: evt.clientY
  10407. };
  10408. if (!noPreventDefault) {
  10409. evt.preventDefault();
  10410. }
  10411. };
  10412. this._onKeyDown = function (evt) {
  10413. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10414. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10415. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10416. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10417. var index = _this._keys.indexOf(evt.keyCode);
  10418. if (index === -1) {
  10419. _this._keys.push(evt.keyCode);
  10420. }
  10421. if (!noPreventDefault) {
  10422. evt.preventDefault();
  10423. }
  10424. }
  10425. };
  10426. this._onKeyUp = function (evt) {
  10427. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10428. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10429. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10430. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10431. var index = _this._keys.indexOf(evt.keyCode);
  10432. if (index >= 0) {
  10433. _this._keys.splice(index, 1);
  10434. }
  10435. if (!noPreventDefault) {
  10436. evt.preventDefault();
  10437. }
  10438. }
  10439. };
  10440. this._onLostFocus = function () {
  10441. _this._keys = [];
  10442. };
  10443. this._reset = function () {
  10444. _this._keys = [];
  10445. previousPosition = null;
  10446. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10447. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10448. };
  10449. }
  10450. element.addEventListener("mousedown", this._onMouseDown, false);
  10451. element.addEventListener("mouseup", this._onMouseUp, false);
  10452. element.addEventListener("mouseout", this._onMouseOut, false);
  10453. element.addEventListener("mousemove", this._onMouseMove, false);
  10454. BABYLON.Tools.RegisterTopRootEvents([
  10455. { name: "keydown", handler: this._onKeyDown },
  10456. { name: "keyup", handler: this._onKeyUp },
  10457. { name: "blur", handler: this._onLostFocus }
  10458. ]);
  10459. };
  10460. FreeCamera.prototype.detachControl = function (element) {
  10461. if (this._attachedElement != element) {
  10462. return;
  10463. }
  10464. element.removeEventListener("mousedown", this._onMouseDown);
  10465. element.removeEventListener("mouseup", this._onMouseUp);
  10466. element.removeEventListener("mouseout", this._onMouseOut);
  10467. element.removeEventListener("mousemove", this._onMouseMove);
  10468. BABYLON.Tools.UnregisterTopRootEvents([
  10469. { name: "keydown", handler: this._onKeyDown },
  10470. { name: "keyup", handler: this._onKeyUp },
  10471. { name: "blur", handler: this._onLostFocus }
  10472. ]);
  10473. this._attachedElement = null;
  10474. if (this._reset) {
  10475. this._reset();
  10476. }
  10477. };
  10478. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10479. var globalPosition;
  10480. if (this.parent) {
  10481. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10482. }
  10483. else {
  10484. globalPosition = this.position;
  10485. }
  10486. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10487. this._collider.radius = this.ellipsoid;
  10488. //add gravity to the velocity to prevent the dual-collision checking
  10489. if (this.applyGravity) {
  10490. velocity.addInPlace(this.getScene().gravity);
  10491. }
  10492. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10493. };
  10494. FreeCamera.prototype._checkInputs = function () {
  10495. if (!this._localDirection) {
  10496. this._localDirection = BABYLON.Vector3.Zero();
  10497. this._transformedDirection = BABYLON.Vector3.Zero();
  10498. }
  10499. // Keyboard
  10500. for (var index = 0; index < this._keys.length; index++) {
  10501. var keyCode = this._keys[index];
  10502. var speed = this._computeLocalCameraSpeed();
  10503. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10504. this._localDirection.copyFromFloats(-speed, 0, 0);
  10505. }
  10506. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10507. this._localDirection.copyFromFloats(0, 0, speed);
  10508. }
  10509. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10510. this._localDirection.copyFromFloats(speed, 0, 0);
  10511. }
  10512. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10513. this._localDirection.copyFromFloats(0, 0, -speed);
  10514. }
  10515. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10516. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10517. this.cameraDirection.addInPlace(this._transformedDirection);
  10518. }
  10519. _super.prototype._checkInputs.call(this);
  10520. };
  10521. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10522. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10523. };
  10524. FreeCamera.prototype._updatePosition = function () {
  10525. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10526. this._collideWithWorld(this.cameraDirection);
  10527. }
  10528. else {
  10529. this.position.addInPlace(this.cameraDirection);
  10530. }
  10531. };
  10532. return FreeCamera;
  10533. })(BABYLON.TargetCamera);
  10534. BABYLON.FreeCamera = FreeCamera;
  10535. })(BABYLON || (BABYLON = {}));
  10536. //# sourceMappingURL=babylon.freeCamera.js.map
  10537. var __extends = this.__extends || function (d, b) {
  10538. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10539. function __() { this.constructor = d; }
  10540. __.prototype = b.prototype;
  10541. d.prototype = new __();
  10542. };
  10543. var BABYLON;
  10544. (function (BABYLON) {
  10545. var FollowCamera = (function (_super) {
  10546. __extends(FollowCamera, _super);
  10547. function FollowCamera(name, position, scene) {
  10548. _super.call(this, name, position, scene);
  10549. this.radius = 12;
  10550. this.rotationOffset = 0;
  10551. this.heightOffset = 4;
  10552. this.cameraAcceleration = 0.05;
  10553. this.maxCameraSpeed = 20;
  10554. }
  10555. FollowCamera.prototype.getRadians = function (degrees) {
  10556. return degrees * Math.PI / 180;
  10557. };
  10558. FollowCamera.prototype.follow = function (cameraTarget) {
  10559. if (!cameraTarget)
  10560. return;
  10561. var yRotation;
  10562. if (cameraTarget.rotationQuaternion) {
  10563. var rotMatrix = new BABYLON.Matrix();
  10564. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10565. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10566. }
  10567. else {
  10568. yRotation = cameraTarget.rotation.y;
  10569. }
  10570. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10571. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10572. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10573. var dx = targetX - this.position.x;
  10574. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10575. var dz = (targetZ) - this.position.z;
  10576. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10577. var vy = dy * this.cameraAcceleration;
  10578. var vz = dz * this.cameraAcceleration * 2;
  10579. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10580. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10581. }
  10582. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10583. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10584. }
  10585. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10586. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10587. }
  10588. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10589. this.setTarget(cameraTarget.position);
  10590. };
  10591. FollowCamera.prototype._checkInputs = function () {
  10592. _super.prototype._checkInputs.call(this);
  10593. this.follow(this.target);
  10594. };
  10595. return FollowCamera;
  10596. })(BABYLON.TargetCamera);
  10597. BABYLON.FollowCamera = FollowCamera;
  10598. })(BABYLON || (BABYLON = {}));
  10599. //# sourceMappingURL=babylon.followCamera.js.map
  10600. var __extends = this.__extends || function (d, b) {
  10601. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10602. function __() { this.constructor = d; }
  10603. __.prototype = b.prototype;
  10604. d.prototype = new __();
  10605. };
  10606. var BABYLON;
  10607. (function (BABYLON) {
  10608. // We're mainly based on the logic defined into the FreeCamera code
  10609. var TouchCamera = (function (_super) {
  10610. __extends(TouchCamera, _super);
  10611. function TouchCamera(name, position, scene) {
  10612. _super.call(this, name, position, scene);
  10613. this._offsetX = null;
  10614. this._offsetY = null;
  10615. this._pointerCount = 0;
  10616. this._pointerPressed = [];
  10617. this.angularSensibility = 200000.0;
  10618. this.moveSensibility = 500.0;
  10619. }
  10620. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10621. var _this = this;
  10622. var previousPosition;
  10623. if (this._attachedCanvas) {
  10624. return;
  10625. }
  10626. this._attachedCanvas = canvas;
  10627. if (this._onPointerDown === undefined) {
  10628. this._onPointerDown = function (evt) {
  10629. if (!noPreventDefault) {
  10630. evt.preventDefault();
  10631. }
  10632. _this._pointerPressed.push(evt.pointerId);
  10633. if (_this._pointerPressed.length !== 1) {
  10634. return;
  10635. }
  10636. previousPosition = {
  10637. x: evt.clientX,
  10638. y: evt.clientY
  10639. };
  10640. };
  10641. this._onPointerUp = function (evt) {
  10642. if (!noPreventDefault) {
  10643. evt.preventDefault();
  10644. }
  10645. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10646. if (index === -1) {
  10647. return;
  10648. }
  10649. _this._pointerPressed.splice(index, 1);
  10650. if (index != 0) {
  10651. return;
  10652. }
  10653. previousPosition = null;
  10654. _this._offsetX = null;
  10655. _this._offsetY = null;
  10656. };
  10657. this._onPointerMove = function (evt) {
  10658. if (!noPreventDefault) {
  10659. evt.preventDefault();
  10660. }
  10661. if (!previousPosition) {
  10662. return;
  10663. }
  10664. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10665. if (index != 0) {
  10666. return;
  10667. }
  10668. _this._offsetX = evt.clientX - previousPosition.x;
  10669. _this._offsetY = -(evt.clientY - previousPosition.y);
  10670. };
  10671. this._onLostFocus = function () {
  10672. _this._offsetX = null;
  10673. _this._offsetY = null;
  10674. };
  10675. }
  10676. canvas.addEventListener("pointerdown", this._onPointerDown);
  10677. canvas.addEventListener("pointerup", this._onPointerUp);
  10678. canvas.addEventListener("pointerout", this._onPointerUp);
  10679. canvas.addEventListener("pointermove", this._onPointerMove);
  10680. BABYLON.Tools.RegisterTopRootEvents([
  10681. { name: "blur", handler: this._onLostFocus }
  10682. ]);
  10683. };
  10684. TouchCamera.prototype.detachControl = function (canvas) {
  10685. if (this._attachedCanvas != canvas) {
  10686. return;
  10687. }
  10688. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10689. canvas.removeEventListener("pointerup", this._onPointerUp);
  10690. canvas.removeEventListener("pointerout", this._onPointerUp);
  10691. canvas.removeEventListener("pointermove", this._onPointerMove);
  10692. BABYLON.Tools.UnregisterTopRootEvents([
  10693. { name: "blur", handler: this._onLostFocus }
  10694. ]);
  10695. this._attachedCanvas = null;
  10696. };
  10697. TouchCamera.prototype._checkInputs = function () {
  10698. if (!this._offsetX) {
  10699. return;
  10700. }
  10701. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10702. if (this._pointerPressed.length > 1) {
  10703. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10704. }
  10705. else {
  10706. var speed = this._computeLocalCameraSpeed();
  10707. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10708. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10709. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10710. }
  10711. _super.prototype._checkInputs.call(this);
  10712. };
  10713. return TouchCamera;
  10714. })(BABYLON.FreeCamera);
  10715. BABYLON.TouchCamera = TouchCamera;
  10716. })(BABYLON || (BABYLON = {}));
  10717. //# sourceMappingURL=babylon.touchCamera.js.map
  10718. var __extends = this.__extends || function (d, b) {
  10719. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10720. function __() { this.constructor = d; }
  10721. __.prototype = b.prototype;
  10722. d.prototype = new __();
  10723. };
  10724. var BABYLON;
  10725. (function (BABYLON) {
  10726. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10727. var ArcRotateCamera = (function (_super) {
  10728. __extends(ArcRotateCamera, _super);
  10729. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10730. var _this = this;
  10731. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10732. this.alpha = alpha;
  10733. this.beta = beta;
  10734. this.radius = radius;
  10735. this.target = target;
  10736. this.inertialAlphaOffset = 0;
  10737. this.inertialBetaOffset = 0;
  10738. this.inertialRadiusOffset = 0;
  10739. this.lowerAlphaLimit = null;
  10740. this.upperAlphaLimit = null;
  10741. this.lowerBetaLimit = 0.01;
  10742. this.upperBetaLimit = Math.PI;
  10743. this.lowerRadiusLimit = null;
  10744. this.upperRadiusLimit = null;
  10745. this.angularSensibility = 1000.0;
  10746. this.wheelPrecision = 3.0;
  10747. this.pinchPrecision = 2.0;
  10748. this.keysUp = [38];
  10749. this.keysDown = [40];
  10750. this.keysLeft = [37];
  10751. this.keysRight = [39];
  10752. this.zoomOnFactor = 1;
  10753. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10754. this.pinchInwards = true;
  10755. this._keys = [];
  10756. this._viewMatrix = new BABYLON.Matrix();
  10757. this.checkCollisions = false;
  10758. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10759. this._collider = new BABYLON.Collider();
  10760. this._previousPosition = BABYLON.Vector3.Zero();
  10761. this._collisionVelocity = BABYLON.Vector3.Zero();
  10762. this._newPosition = BABYLON.Vector3.Zero();
  10763. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10764. if (collidedMesh === void 0) { collidedMesh = null; }
  10765. if (collisionId != null || collisionId != undefined)
  10766. newPosition.multiplyInPlace(_this._collider.radius);
  10767. if (!newPosition.equalsWithEpsilon(_this.position)) {
  10768. _this.position.copyFrom(_this._previousPosition);
  10769. _this.alpha = _this._previousAlpha;
  10770. _this.beta = _this._previousBeta;
  10771. _this.radius = _this._previousRadius;
  10772. if (_this.onCollide && collidedMesh) {
  10773. _this.onCollide(collidedMesh);
  10774. }
  10775. }
  10776. _this._collisionTriggered = false;
  10777. };
  10778. if (!this.target) {
  10779. this.target = BABYLON.Vector3.Zero();
  10780. }
  10781. this.getViewMatrix();
  10782. }
  10783. ArcRotateCamera.prototype._getTargetPosition = function () {
  10784. return this.target.position || this.target;
  10785. };
  10786. // Cache
  10787. ArcRotateCamera.prototype._initCache = function () {
  10788. _super.prototype._initCache.call(this);
  10789. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10790. this._cache.alpha = undefined;
  10791. this._cache.beta = undefined;
  10792. this._cache.radius = undefined;
  10793. this._cache.targetScreenOffset = undefined;
  10794. };
  10795. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10796. if (!ignoreParentClass) {
  10797. _super.prototype._updateCache.call(this);
  10798. }
  10799. this._cache.target.copyFrom(this._getTargetPosition());
  10800. this._cache.alpha = this.alpha;
  10801. this._cache.beta = this.beta;
  10802. this._cache.radius = this.radius;
  10803. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10804. };
  10805. // Synchronized
  10806. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10807. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10808. return false;
  10809. return this._cache.target.equals(this._getTargetPosition())
  10810. && this._cache.alpha === this.alpha
  10811. && this._cache.beta === this.beta
  10812. && this._cache.radius === this.radius
  10813. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10814. };
  10815. // Methods
  10816. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  10817. var _this = this;
  10818. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10819. var previousPinchDistance = 0;
  10820. var pointers = new BABYLON.SmartCollection();
  10821. if (this._attachedElement) {
  10822. return;
  10823. }
  10824. this._attachedElement = element;
  10825. var engine = this.getEngine();
  10826. if (this._onPointerDown === undefined) {
  10827. this._onPointerDown = function (evt) {
  10828. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10829. cacheSoloPointer = pointers.item(evt.pointerId);
  10830. if (!noPreventDefault) {
  10831. evt.preventDefault();
  10832. }
  10833. };
  10834. this._onPointerUp = function (evt) {
  10835. cacheSoloPointer = null;
  10836. previousPinchDistance = 0;
  10837. pointers.remove(evt.pointerId);
  10838. if (!noPreventDefault) {
  10839. evt.preventDefault();
  10840. }
  10841. };
  10842. this._onPointerMove = function (evt) {
  10843. if (!noPreventDefault) {
  10844. evt.preventDefault();
  10845. }
  10846. switch (pointers.count) {
  10847. case 1:
  10848. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  10849. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  10850. var offsetX = evt.clientX - cacheSoloPointer.x;
  10851. var offsetY = evt.clientY - cacheSoloPointer.y;
  10852. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10853. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10854. //pointers.item(evt.pointerId).x = evt.clientX;
  10855. //pointers.item(evt.pointerId).y = evt.clientY;
  10856. cacheSoloPointer.x = evt.clientX;
  10857. cacheSoloPointer.y = evt.clientY;
  10858. break;
  10859. case 2:
  10860. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10861. pointers.item(evt.pointerId).x = evt.clientX;
  10862. pointers.item(evt.pointerId).y = evt.clientY;
  10863. var direction = _this.pinchInwards ? 1 : -1;
  10864. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10865. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10866. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10867. if (previousPinchDistance === 0) {
  10868. previousPinchDistance = pinchSquaredDistance;
  10869. return;
  10870. }
  10871. if (pinchSquaredDistance !== previousPinchDistance) {
  10872. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  10873. previousPinchDistance = pinchSquaredDistance;
  10874. }
  10875. break;
  10876. default:
  10877. if (pointers.item(evt.pointerId)) {
  10878. pointers.item(evt.pointerId).x = evt.clientX;
  10879. pointers.item(evt.pointerId).y = evt.clientY;
  10880. }
  10881. }
  10882. };
  10883. this._onMouseMove = function (evt) {
  10884. if (!engine.isPointerLock) {
  10885. return;
  10886. }
  10887. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10888. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10889. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10890. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10891. if (!noPreventDefault) {
  10892. evt.preventDefault();
  10893. }
  10894. };
  10895. this._wheel = function (event) {
  10896. var delta = 0;
  10897. if (event.wheelDelta) {
  10898. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10899. }
  10900. else if (event.detail) {
  10901. delta = -event.detail / _this.wheelPrecision;
  10902. }
  10903. if (delta)
  10904. _this.inertialRadiusOffset += delta;
  10905. if (event.preventDefault) {
  10906. if (!noPreventDefault) {
  10907. event.preventDefault();
  10908. }
  10909. }
  10910. };
  10911. this._onKeyDown = function (evt) {
  10912. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10913. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10914. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10915. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10916. var index = _this._keys.indexOf(evt.keyCode);
  10917. if (index === -1) {
  10918. _this._keys.push(evt.keyCode);
  10919. }
  10920. if (evt.preventDefault) {
  10921. if (!noPreventDefault) {
  10922. evt.preventDefault();
  10923. }
  10924. }
  10925. }
  10926. };
  10927. this._onKeyUp = function (evt) {
  10928. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10929. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10930. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10931. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10932. var index = _this._keys.indexOf(evt.keyCode);
  10933. if (index >= 0) {
  10934. _this._keys.splice(index, 1);
  10935. }
  10936. if (evt.preventDefault) {
  10937. if (!noPreventDefault) {
  10938. evt.preventDefault();
  10939. }
  10940. }
  10941. }
  10942. };
  10943. this._onLostFocus = function () {
  10944. _this._keys = [];
  10945. pointers.empty();
  10946. previousPinchDistance = 0;
  10947. cacheSoloPointer = null;
  10948. };
  10949. this._onGestureStart = function (e) {
  10950. if (window.MSGesture === undefined) {
  10951. return;
  10952. }
  10953. if (!_this._MSGestureHandler) {
  10954. _this._MSGestureHandler = new MSGesture();
  10955. _this._MSGestureHandler.target = element;
  10956. }
  10957. _this._MSGestureHandler.addPointer(e.pointerId);
  10958. };
  10959. this._onGesture = function (e) {
  10960. _this.radius *= e.scale;
  10961. if (e.preventDefault) {
  10962. if (!noPreventDefault) {
  10963. e.stopPropagation();
  10964. e.preventDefault();
  10965. }
  10966. }
  10967. };
  10968. this._reset = function () {
  10969. _this._keys = [];
  10970. _this.inertialAlphaOffset = 0;
  10971. _this.inertialBetaOffset = 0;
  10972. _this.inertialRadiusOffset = 0;
  10973. pointers.empty();
  10974. previousPinchDistance = 0;
  10975. cacheSoloPointer = null;
  10976. };
  10977. }
  10978. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10979. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10980. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10981. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10982. element.addEventListener("mousemove", this._onMouseMove, false);
  10983. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10984. element.addEventListener("MSGestureChange", this._onGesture, false);
  10985. element.addEventListener('mousewheel', this._wheel, false);
  10986. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10987. BABYLON.Tools.RegisterTopRootEvents([
  10988. { name: "keydown", handler: this._onKeyDown },
  10989. { name: "keyup", handler: this._onKeyUp },
  10990. { name: "blur", handler: this._onLostFocus }
  10991. ]);
  10992. };
  10993. ArcRotateCamera.prototype.detachControl = function (element) {
  10994. if (this._attachedElement !== element) {
  10995. return;
  10996. }
  10997. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  10998. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  10999. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11000. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11001. element.removeEventListener("mousemove", this._onMouseMove);
  11002. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11003. element.removeEventListener("MSGestureChange", this._onGesture);
  11004. element.removeEventListener('mousewheel', this._wheel);
  11005. element.removeEventListener('DOMMouseScroll', this._wheel);
  11006. BABYLON.Tools.UnregisterTopRootEvents([
  11007. { name: "keydown", handler: this._onKeyDown },
  11008. { name: "keyup", handler: this._onKeyUp },
  11009. { name: "blur", handler: this._onLostFocus }
  11010. ]);
  11011. this._MSGestureHandler = null;
  11012. this._attachedElement = null;
  11013. if (this._reset) {
  11014. this._reset();
  11015. }
  11016. };
  11017. ArcRotateCamera.prototype._checkInputs = function () {
  11018. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11019. if (this._collisionTriggered) {
  11020. return;
  11021. }
  11022. // Keyboard
  11023. for (var index = 0; index < this._keys.length; index++) {
  11024. var keyCode = this._keys[index];
  11025. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11026. this.inertialAlphaOffset -= 0.01;
  11027. }
  11028. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11029. this.inertialBetaOffset -= 0.01;
  11030. }
  11031. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11032. this.inertialAlphaOffset += 0.01;
  11033. }
  11034. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11035. this.inertialBetaOffset += 0.01;
  11036. }
  11037. }
  11038. // Inertia
  11039. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11040. this.alpha += this.inertialAlphaOffset;
  11041. this.beta += this.inertialBetaOffset;
  11042. this.radius -= this.inertialRadiusOffset;
  11043. this.inertialAlphaOffset *= this.inertia;
  11044. this.inertialBetaOffset *= this.inertia;
  11045. this.inertialRadiusOffset *= this.inertia;
  11046. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11047. this.inertialAlphaOffset = 0;
  11048. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11049. this.inertialBetaOffset = 0;
  11050. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11051. this.inertialRadiusOffset = 0;
  11052. }
  11053. // Limits
  11054. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11055. this.alpha = this.lowerAlphaLimit;
  11056. }
  11057. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11058. this.alpha = this.upperAlphaLimit;
  11059. }
  11060. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  11061. this.beta = this.lowerBetaLimit;
  11062. }
  11063. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  11064. this.beta = this.upperBetaLimit;
  11065. }
  11066. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11067. this.radius = this.lowerRadiusLimit;
  11068. }
  11069. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11070. this.radius = this.upperRadiusLimit;
  11071. }
  11072. _super.prototype._checkInputs.call(this);
  11073. };
  11074. ArcRotateCamera.prototype.setPosition = function (position) {
  11075. var radiusv3 = position.subtract(this._getTargetPosition());
  11076. this.radius = radiusv3.length();
  11077. // Alpha
  11078. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11079. if (radiusv3.z < 0) {
  11080. this.alpha = 2 * Math.PI - this.alpha;
  11081. }
  11082. // Beta
  11083. this.beta = Math.acos(radiusv3.y / this.radius);
  11084. };
  11085. ArcRotateCamera.prototype._getViewMatrix = function () {
  11086. // Compute
  11087. var cosa = Math.cos(this.alpha);
  11088. var sina = Math.sin(this.alpha);
  11089. var cosb = Math.cos(this.beta);
  11090. var sinb = Math.sin(this.beta);
  11091. var target = this._getTargetPosition();
  11092. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  11093. if (this.checkCollisions) {
  11094. this._collider.radius = this.collisionRadius;
  11095. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  11096. this._collisionTriggered = true;
  11097. this.getScene().collisionCoordinator.getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11098. }
  11099. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  11100. this._previousAlpha = this.alpha;
  11101. this._previousBeta = this.beta;
  11102. this._previousRadius = this.radius;
  11103. this._previousPosition.copyFrom(this.position);
  11104. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11105. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11106. return this._viewMatrix;
  11107. };
  11108. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  11109. meshes = meshes || this.getScene().meshes;
  11110. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11111. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11112. this.radius = distance * this.zoomOnFactor;
  11113. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  11114. };
  11115. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  11116. var meshesOrMinMaxVector;
  11117. var distance;
  11118. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11119. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11120. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11121. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11122. }
  11123. else {
  11124. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11125. distance = meshesOrMinMaxVectorAndDistance.distance;
  11126. }
  11127. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11128. this.maxZ = distance * 2;
  11129. };
  11130. /**
  11131. * @override
  11132. * needs to be overridden, so sub has required properties to be copied
  11133. */
  11134. ArcRotateCamera.prototype.getSubCamera = function (name, isA) {
  11135. var alphaSpace = this._subCamHalfSpace * (isA ? -1 : 1);
  11136. return new BABYLON.ArcRotateCamera(name, this.alpha + alphaSpace, this.beta, this.radius, this.target, this.getScene());
  11137. };
  11138. /**
  11139. * @override
  11140. * needs to be overridden, adding copy of alpha, beta & radius
  11141. */
  11142. ArcRotateCamera.prototype._updateSubCameras = function () {
  11143. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  11144. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  11145. camA.alpha = this.alpha - this._subCamHalfSpace;
  11146. camB.alpha = this.alpha + this._subCamHalfSpace;
  11147. camA.beta = camB.beta = this.beta;
  11148. camA.radius = camB.radius = this.radius;
  11149. _super.prototype._updateSubCameras.call(this);
  11150. };
  11151. return ArcRotateCamera;
  11152. })(BABYLON.Camera);
  11153. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11154. })(BABYLON || (BABYLON = {}));
  11155. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  11156. var __extends = this.__extends || function (d, b) {
  11157. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11158. function __() { this.constructor = d; }
  11159. __.prototype = b.prototype;
  11160. d.prototype = new __();
  11161. };
  11162. var BABYLON;
  11163. (function (BABYLON) {
  11164. // We're mainly based on the logic defined into the FreeCamera code
  11165. var DeviceOrientationCamera = (function (_super) {
  11166. __extends(DeviceOrientationCamera, _super);
  11167. function DeviceOrientationCamera(name, position, scene) {
  11168. var _this = this;
  11169. _super.call(this, name, position, scene);
  11170. this._offsetX = null;
  11171. this._offsetY = null;
  11172. this._orientationGamma = 0;
  11173. this._orientationBeta = 0;
  11174. this._initialOrientationGamma = 0;
  11175. this._initialOrientationBeta = 0;
  11176. this.angularSensibility = 10000.0;
  11177. this.moveSensibility = 50.0;
  11178. window.addEventListener("resize", function () {
  11179. _this._initialOrientationGamma = null;
  11180. }, false);
  11181. }
  11182. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11183. var _this = this;
  11184. if (this._attachedCanvas) {
  11185. return;
  11186. }
  11187. this._attachedCanvas = canvas;
  11188. if (!this._orientationChanged) {
  11189. this._orientationChanged = function (evt) {
  11190. if (!_this._initialOrientationGamma) {
  11191. _this._initialOrientationGamma = evt.gamma;
  11192. _this._initialOrientationBeta = evt.beta;
  11193. }
  11194. _this._orientationGamma = evt.gamma;
  11195. _this._orientationBeta = evt.beta;
  11196. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11197. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11198. };
  11199. }
  11200. window.addEventListener("deviceorientation", this._orientationChanged);
  11201. };
  11202. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11203. if (this._attachedCanvas != canvas) {
  11204. return;
  11205. }
  11206. window.removeEventListener("deviceorientation", this._orientationChanged);
  11207. this._attachedCanvas = null;
  11208. this._orientationGamma = 0;
  11209. this._orientationBeta = 0;
  11210. this._initialOrientationGamma = 0;
  11211. this._initialOrientationBeta = 0;
  11212. };
  11213. DeviceOrientationCamera.prototype._checkInputs = function () {
  11214. if (!this._offsetX) {
  11215. return;
  11216. }
  11217. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11218. var speed = this._computeLocalCameraSpeed();
  11219. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11220. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11221. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11222. _super.prototype._checkInputs.call(this);
  11223. };
  11224. return DeviceOrientationCamera;
  11225. })(BABYLON.FreeCamera);
  11226. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11227. })(BABYLON || (BABYLON = {}));
  11228. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  11229. var __extends = this.__extends || function (d, b) {
  11230. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11231. function __() { this.constructor = d; }
  11232. __.prototype = b.prototype;
  11233. d.prototype = new __();
  11234. };
  11235. var BABYLON;
  11236. (function (BABYLON) {
  11237. var Gamepads = (function () {
  11238. function Gamepads(ongamedpadconnected) {
  11239. var _this = this;
  11240. this.babylonGamepads = [];
  11241. this.oneGamepadConnected = false;
  11242. this.isMonitoring = false;
  11243. this.gamepadEventSupported = 'GamepadEvent' in window;
  11244. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11245. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11246. 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=";
  11247. this._callbackGamepadConnected = ongamedpadconnected;
  11248. if (this.gamepadSupportAvailable) {
  11249. // Checking if the gamepad connected event is supported (like in Firefox)
  11250. if (this.gamepadEventSupported) {
  11251. window.addEventListener('gamepadconnected', function (evt) {
  11252. _this._onGamepadConnected(evt);
  11253. }, false);
  11254. window.addEventListener('gamepaddisconnected', function (evt) {
  11255. _this._onGamepadDisconnected(evt);
  11256. }, false);
  11257. }
  11258. else {
  11259. this._startMonitoringGamepads();
  11260. }
  11261. if (!this.oneGamepadConnected) {
  11262. this._insertGamepadDOMInstructions();
  11263. }
  11264. }
  11265. else {
  11266. this._insertGamepadDOMNotSupported();
  11267. }
  11268. }
  11269. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11270. Gamepads.gamepadDOMInfo = document.createElement("div");
  11271. var buttonAImage = document.createElement("img");
  11272. buttonAImage.src = this.buttonADataURL;
  11273. var spanMessage = document.createElement("span");
  11274. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11275. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11276. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11277. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11278. Gamepads.gamepadDOMInfo.style.width = "100%";
  11279. Gamepads.gamepadDOMInfo.style.height = "48px";
  11280. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11281. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11282. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11283. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11284. buttonAImage.style.position = "relative";
  11285. buttonAImage.style.bottom = "8px";
  11286. spanMessage.style.position = "relative";
  11287. spanMessage.style.fontSize = "32px";
  11288. spanMessage.style.bottom = "32px";
  11289. spanMessage.style.color = "green";
  11290. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11291. };
  11292. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11293. Gamepads.gamepadDOMInfo = document.createElement("div");
  11294. var spanMessage = document.createElement("span");
  11295. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11296. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11297. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11298. Gamepads.gamepadDOMInfo.style.width = "100%";
  11299. Gamepads.gamepadDOMInfo.style.height = "40px";
  11300. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11301. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11302. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11303. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11304. spanMessage.style.position = "relative";
  11305. spanMessage.style.fontSize = "32px";
  11306. spanMessage.style.color = "red";
  11307. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11308. };
  11309. Gamepads.prototype.dispose = function () {
  11310. if (Gamepads.gamepadDOMInfo) {
  11311. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11312. }
  11313. };
  11314. Gamepads.prototype._onGamepadConnected = function (evt) {
  11315. var newGamepad = this._addNewGamepad(evt.gamepad);
  11316. if (this._callbackGamepadConnected)
  11317. this._callbackGamepadConnected(newGamepad);
  11318. this._startMonitoringGamepads();
  11319. };
  11320. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11321. if (!this.oneGamepadConnected) {
  11322. this.oneGamepadConnected = true;
  11323. if (Gamepads.gamepadDOMInfo) {
  11324. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11325. Gamepads.gamepadDOMInfo = null;
  11326. }
  11327. }
  11328. var newGamepad;
  11329. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11330. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11331. }
  11332. else {
  11333. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  11334. }
  11335. this.babylonGamepads.push(newGamepad);
  11336. return newGamepad;
  11337. };
  11338. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11339. // Remove the gamepad from the list of gamepads to monitor.
  11340. for (var i in this.babylonGamepads) {
  11341. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11342. this.babylonGamepads.splice(i, 1);
  11343. break;
  11344. }
  11345. }
  11346. // If no gamepads are left, stop the polling loop.
  11347. if (this.babylonGamepads.length == 0) {
  11348. this._stopMonitoringGamepads();
  11349. }
  11350. };
  11351. Gamepads.prototype._startMonitoringGamepads = function () {
  11352. if (!this.isMonitoring) {
  11353. this.isMonitoring = true;
  11354. this._checkGamepadsStatus();
  11355. }
  11356. };
  11357. Gamepads.prototype._stopMonitoringGamepads = function () {
  11358. this.isMonitoring = false;
  11359. };
  11360. Gamepads.prototype._checkGamepadsStatus = function () {
  11361. var _this = this;
  11362. // updating gamepad objects
  11363. this._updateGamepadObjects();
  11364. for (var i in this.babylonGamepads) {
  11365. this.babylonGamepads[i].update();
  11366. }
  11367. if (this.isMonitoring) {
  11368. if (window.requestAnimationFrame) {
  11369. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11370. }
  11371. else if (window.mozRequestAnimationFrame) {
  11372. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11373. }
  11374. else if (window.webkitRequestAnimationFrame) {
  11375. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11376. }
  11377. }
  11378. };
  11379. // This function is called only on Chrome, which does not yet support
  11380. // connection/disconnection events, but requires you to monitor
  11381. // an array for changes.
  11382. Gamepads.prototype._updateGamepadObjects = function () {
  11383. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11384. for (var i = 0; i < gamepads.length; i++) {
  11385. if (gamepads[i]) {
  11386. if (!(gamepads[i].index in this.babylonGamepads)) {
  11387. var newGamepad = this._addNewGamepad(gamepads[i]);
  11388. if (this._callbackGamepadConnected) {
  11389. this._callbackGamepadConnected(newGamepad);
  11390. }
  11391. }
  11392. else {
  11393. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11394. }
  11395. }
  11396. }
  11397. };
  11398. return Gamepads;
  11399. })();
  11400. BABYLON.Gamepads = Gamepads;
  11401. var StickValues = (function () {
  11402. function StickValues(x, y) {
  11403. this.x = x;
  11404. this.y = y;
  11405. }
  11406. return StickValues;
  11407. })();
  11408. BABYLON.StickValues = StickValues;
  11409. var Gamepad = (function () {
  11410. function Gamepad(id, index, browserGamepad) {
  11411. this.id = id;
  11412. this.index = index;
  11413. this.browserGamepad = browserGamepad;
  11414. if (this.browserGamepad.axes.length >= 2) {
  11415. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11416. }
  11417. if (this.browserGamepad.axes.length >= 4) {
  11418. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11419. }
  11420. }
  11421. Gamepad.prototype.onleftstickchanged = function (callback) {
  11422. this._onleftstickchanged = callback;
  11423. };
  11424. Gamepad.prototype.onrightstickchanged = function (callback) {
  11425. this._onrightstickchanged = callback;
  11426. };
  11427. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11428. get: function () {
  11429. return this._leftStick;
  11430. },
  11431. set: function (newValues) {
  11432. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11433. this._onleftstickchanged(newValues);
  11434. }
  11435. this._leftStick = newValues;
  11436. },
  11437. enumerable: true,
  11438. configurable: true
  11439. });
  11440. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11441. get: function () {
  11442. return this._rightStick;
  11443. },
  11444. set: function (newValues) {
  11445. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11446. this._onrightstickchanged(newValues);
  11447. }
  11448. this._rightStick = newValues;
  11449. },
  11450. enumerable: true,
  11451. configurable: true
  11452. });
  11453. Gamepad.prototype.update = function () {
  11454. if (this._leftStick) {
  11455. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11456. }
  11457. if (this._rightStick) {
  11458. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11459. }
  11460. };
  11461. return Gamepad;
  11462. })();
  11463. BABYLON.Gamepad = Gamepad;
  11464. var GenericPad = (function (_super) {
  11465. __extends(GenericPad, _super);
  11466. function GenericPad(id, index, gamepad) {
  11467. _super.call(this, id, index, gamepad);
  11468. this.id = id;
  11469. this.index = index;
  11470. this.gamepad = gamepad;
  11471. this._buttons = new Array(gamepad.buttons.length);
  11472. }
  11473. GenericPad.prototype.onbuttondown = function (callback) {
  11474. this._onbuttondown = callback;
  11475. };
  11476. GenericPad.prototype.onbuttonup = function (callback) {
  11477. this._onbuttonup = callback;
  11478. };
  11479. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11480. if (newValue !== currentValue) {
  11481. if (this._onbuttondown && newValue === 1) {
  11482. this._onbuttondown(buttonIndex);
  11483. }
  11484. if (this._onbuttonup && newValue === 0) {
  11485. this._onbuttonup(buttonIndex);
  11486. }
  11487. }
  11488. return newValue;
  11489. };
  11490. GenericPad.prototype.update = function () {
  11491. _super.prototype.update.call(this);
  11492. for (var index = 0; index < this._buttons.length; index++) {
  11493. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11494. }
  11495. };
  11496. return GenericPad;
  11497. })(Gamepad);
  11498. BABYLON.GenericPad = GenericPad;
  11499. (function (Xbox360Button) {
  11500. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11501. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11502. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11503. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11504. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11505. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11506. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11507. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11508. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11509. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11510. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11511. var Xbox360Button = BABYLON.Xbox360Button;
  11512. (function (Xbox360Dpad) {
  11513. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11514. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11515. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11516. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11517. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11518. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11519. var Xbox360Pad = (function (_super) {
  11520. __extends(Xbox360Pad, _super);
  11521. function Xbox360Pad() {
  11522. _super.apply(this, arguments);
  11523. this._leftTrigger = 0;
  11524. this._rightTrigger = 0;
  11525. this._buttonA = 0;
  11526. this._buttonB = 0;
  11527. this._buttonX = 0;
  11528. this._buttonY = 0;
  11529. this._buttonBack = 0;
  11530. this._buttonStart = 0;
  11531. this._buttonLB = 0;
  11532. this._buttonRB = 0;
  11533. this._buttonLeftStick = 0;
  11534. this._buttonRightStick = 0;
  11535. this._dPadUp = 0;
  11536. this._dPadDown = 0;
  11537. this._dPadLeft = 0;
  11538. this._dPadRight = 0;
  11539. }
  11540. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11541. this._onlefttriggerchanged = callback;
  11542. };
  11543. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11544. this._onrighttriggerchanged = callback;
  11545. };
  11546. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11547. get: function () {
  11548. return this._leftTrigger;
  11549. },
  11550. set: function (newValue) {
  11551. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11552. this._onlefttriggerchanged(newValue);
  11553. }
  11554. this._leftTrigger = newValue;
  11555. },
  11556. enumerable: true,
  11557. configurable: true
  11558. });
  11559. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11560. get: function () {
  11561. return this._rightTrigger;
  11562. },
  11563. set: function (newValue) {
  11564. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11565. this._onrighttriggerchanged(newValue);
  11566. }
  11567. this._rightTrigger = newValue;
  11568. },
  11569. enumerable: true,
  11570. configurable: true
  11571. });
  11572. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11573. this._onbuttondown = callback;
  11574. };
  11575. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11576. this._onbuttonup = callback;
  11577. };
  11578. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11579. this._ondpaddown = callback;
  11580. };
  11581. Xbox360Pad.prototype.ondpadup = function (callback) {
  11582. this._ondpadup = callback;
  11583. };
  11584. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11585. if (newValue !== currentValue) {
  11586. if (this._onbuttondown && newValue === 1) {
  11587. this._onbuttondown(buttonType);
  11588. }
  11589. if (this._onbuttonup && newValue === 0) {
  11590. this._onbuttonup(buttonType);
  11591. }
  11592. }
  11593. return newValue;
  11594. };
  11595. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11596. if (newValue !== currentValue) {
  11597. if (this._ondpaddown && newValue === 1) {
  11598. this._ondpaddown(buttonType);
  11599. }
  11600. if (this._ondpadup && newValue === 0) {
  11601. this._ondpadup(buttonType);
  11602. }
  11603. }
  11604. return newValue;
  11605. };
  11606. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11607. get: function () {
  11608. return this._buttonA;
  11609. },
  11610. set: function (value) {
  11611. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11612. },
  11613. enumerable: true,
  11614. configurable: true
  11615. });
  11616. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11617. get: function () {
  11618. return this._buttonB;
  11619. },
  11620. set: function (value) {
  11621. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11627. get: function () {
  11628. return this._buttonX;
  11629. },
  11630. set: function (value) {
  11631. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11632. },
  11633. enumerable: true,
  11634. configurable: true
  11635. });
  11636. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11637. get: function () {
  11638. return this._buttonY;
  11639. },
  11640. set: function (value) {
  11641. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11642. },
  11643. enumerable: true,
  11644. configurable: true
  11645. });
  11646. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11647. get: function () {
  11648. return this._buttonStart;
  11649. },
  11650. set: function (value) {
  11651. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  11652. },
  11653. enumerable: true,
  11654. configurable: true
  11655. });
  11656. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  11657. get: function () {
  11658. return this._buttonBack;
  11659. },
  11660. set: function (value) {
  11661. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  11662. },
  11663. enumerable: true,
  11664. configurable: true
  11665. });
  11666. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  11667. get: function () {
  11668. return this._buttonLB;
  11669. },
  11670. set: function (value) {
  11671. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  11672. },
  11673. enumerable: true,
  11674. configurable: true
  11675. });
  11676. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  11677. get: function () {
  11678. return this._buttonRB;
  11679. },
  11680. set: function (value) {
  11681. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  11682. },
  11683. enumerable: true,
  11684. configurable: true
  11685. });
  11686. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  11687. get: function () {
  11688. return this._buttonLeftStick;
  11689. },
  11690. set: function (value) {
  11691. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  11692. },
  11693. enumerable: true,
  11694. configurable: true
  11695. });
  11696. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  11697. get: function () {
  11698. return this._buttonRightStick;
  11699. },
  11700. set: function (value) {
  11701. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  11707. get: function () {
  11708. return this._dPadUp;
  11709. },
  11710. set: function (value) {
  11711. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  11717. get: function () {
  11718. return this._dPadDown;
  11719. },
  11720. set: function (value) {
  11721. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  11722. },
  11723. enumerable: true,
  11724. configurable: true
  11725. });
  11726. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  11727. get: function () {
  11728. return this._dPadLeft;
  11729. },
  11730. set: function (value) {
  11731. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  11732. },
  11733. enumerable: true,
  11734. configurable: true
  11735. });
  11736. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  11737. get: function () {
  11738. return this._dPadRight;
  11739. },
  11740. set: function (value) {
  11741. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  11742. },
  11743. enumerable: true,
  11744. configurable: true
  11745. });
  11746. Xbox360Pad.prototype.update = function () {
  11747. _super.prototype.update.call(this);
  11748. this.buttonA = this.browserGamepad.buttons[0].value;
  11749. this.buttonB = this.browserGamepad.buttons[1].value;
  11750. this.buttonX = this.browserGamepad.buttons[2].value;
  11751. this.buttonY = this.browserGamepad.buttons[3].value;
  11752. this.buttonLB = this.browserGamepad.buttons[4].value;
  11753. this.buttonRB = this.browserGamepad.buttons[5].value;
  11754. this.leftTrigger = this.browserGamepad.buttons[6].value;
  11755. this.rightTrigger = this.browserGamepad.buttons[7].value;
  11756. this.buttonBack = this.browserGamepad.buttons[8].value;
  11757. this.buttonStart = this.browserGamepad.buttons[9].value;
  11758. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  11759. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  11760. this.dPadUp = this.browserGamepad.buttons[12].value;
  11761. this.dPadDown = this.browserGamepad.buttons[13].value;
  11762. this.dPadLeft = this.browserGamepad.buttons[14].value;
  11763. this.dPadRight = this.browserGamepad.buttons[15].value;
  11764. };
  11765. return Xbox360Pad;
  11766. })(Gamepad);
  11767. BABYLON.Xbox360Pad = Xbox360Pad;
  11768. })(BABYLON || (BABYLON = {}));
  11769. //# sourceMappingURL=babylon.gamepads.js.map
  11770. var __extends = this.__extends || function (d, b) {
  11771. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11772. function __() { this.constructor = d; }
  11773. __.prototype = b.prototype;
  11774. d.prototype = new __();
  11775. };
  11776. var BABYLON;
  11777. (function (BABYLON) {
  11778. // We're mainly based on the logic defined into the FreeCamera code
  11779. var GamepadCamera = (function (_super) {
  11780. __extends(GamepadCamera, _super);
  11781. function GamepadCamera(name, position, scene) {
  11782. var _this = this;
  11783. _super.call(this, name, position, scene);
  11784. this.angularSensibility = 200;
  11785. this.moveSensibility = 75;
  11786. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  11787. }
  11788. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  11789. // Only the first gamepad can control the camera
  11790. if (gamepad.index === 0) {
  11791. this._gamepad = gamepad;
  11792. }
  11793. };
  11794. GamepadCamera.prototype._checkInputs = function () {
  11795. if (this._gamepad) {
  11796. var LSValues = this._gamepad.leftStick;
  11797. var normalizedLX = LSValues.x / this.moveSensibility;
  11798. var normalizedLY = LSValues.y / this.moveSensibility;
  11799. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  11800. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  11801. var RSValues = this._gamepad.rightStick;
  11802. var normalizedRX = RSValues.x / this.angularSensibility;
  11803. var normalizedRY = RSValues.y / this.angularSensibility;
  11804. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  11805. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  11806. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  11807. var speed = this._computeLocalCameraSpeed() * 50.0;
  11808. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  11809. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  11810. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  11811. }
  11812. _super.prototype._checkInputs.call(this);
  11813. };
  11814. GamepadCamera.prototype.dispose = function () {
  11815. this._gamepads.dispose();
  11816. _super.prototype.dispose.call(this);
  11817. };
  11818. return GamepadCamera;
  11819. })(BABYLON.FreeCamera);
  11820. BABYLON.GamepadCamera = GamepadCamera;
  11821. })(BABYLON || (BABYLON = {}));
  11822. //# sourceMappingURL=babylon.gamepadCamera.js.map
  11823. var BABYLON;
  11824. (function (BABYLON) {
  11825. var RenderingManager = (function () {
  11826. function RenderingManager(scene) {
  11827. this._renderingGroups = new Array();
  11828. this._scene = scene;
  11829. }
  11830. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11831. if (this._scene._activeParticleSystems.length === 0) {
  11832. return;
  11833. }
  11834. // Particles
  11835. var beforeParticlesDate = BABYLON.Tools.Now;
  11836. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11837. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11838. if (particleSystem.renderingGroupId !== index) {
  11839. continue;
  11840. }
  11841. this._clearDepthBuffer();
  11842. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11843. this._scene._activeParticles += particleSystem.render();
  11844. }
  11845. }
  11846. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11847. };
  11848. RenderingManager.prototype._renderSprites = function (index) {
  11849. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11850. return;
  11851. }
  11852. // Sprites
  11853. var beforeSpritessDate = BABYLON.Tools.Now;
  11854. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11855. var spriteManager = this._scene.spriteManagers[id];
  11856. if (spriteManager.renderingGroupId === index) {
  11857. this._clearDepthBuffer();
  11858. spriteManager.render();
  11859. }
  11860. }
  11861. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11862. };
  11863. RenderingManager.prototype._clearDepthBuffer = function () {
  11864. if (this._depthBufferAlreadyCleaned) {
  11865. return;
  11866. }
  11867. this._scene.getEngine().clear(0, false, true);
  11868. this._depthBufferAlreadyCleaned = true;
  11869. };
  11870. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11871. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11872. this._depthBufferAlreadyCleaned = false;
  11873. var renderingGroup = this._renderingGroups[index];
  11874. var needToStepBack = false;
  11875. if (renderingGroup) {
  11876. this._clearDepthBuffer();
  11877. if (!renderingGroup.render(customRenderFunction)) {
  11878. this._renderingGroups.splice(index, 1);
  11879. needToStepBack = true;
  11880. }
  11881. }
  11882. if (renderSprites) {
  11883. this._renderSprites(index);
  11884. }
  11885. if (renderParticles) {
  11886. this._renderParticles(index, activeMeshes);
  11887. }
  11888. if (needToStepBack) {
  11889. index--;
  11890. }
  11891. }
  11892. };
  11893. RenderingManager.prototype.reset = function () {
  11894. for (var index in this._renderingGroups) {
  11895. var renderingGroup = this._renderingGroups[index];
  11896. renderingGroup.prepare();
  11897. }
  11898. };
  11899. RenderingManager.prototype.dispatch = function (subMesh) {
  11900. var mesh = subMesh.getMesh();
  11901. var renderingGroupId = mesh.renderingGroupId || 0;
  11902. if (!this._renderingGroups[renderingGroupId]) {
  11903. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11904. }
  11905. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11906. };
  11907. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11908. return RenderingManager;
  11909. })();
  11910. BABYLON.RenderingManager = RenderingManager;
  11911. })(BABYLON || (BABYLON = {}));
  11912. //# sourceMappingURL=babylon.renderingManager.js.map
  11913. var BABYLON;
  11914. (function (BABYLON) {
  11915. var RenderingGroup = (function () {
  11916. function RenderingGroup(index, scene) {
  11917. this.index = index;
  11918. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11919. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11920. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11921. this._scene = scene;
  11922. }
  11923. RenderingGroup.prototype.render = function (customRenderFunction) {
  11924. if (customRenderFunction) {
  11925. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11926. return true;
  11927. }
  11928. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11929. return false;
  11930. }
  11931. var engine = this._scene.getEngine();
  11932. // Opaque
  11933. var subIndex;
  11934. var submesh;
  11935. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11936. submesh = this._opaqueSubMeshes.data[subIndex];
  11937. submesh.render();
  11938. }
  11939. // Alpha test
  11940. engine.setAlphaTesting(true);
  11941. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11942. submesh = this._alphaTestSubMeshes.data[subIndex];
  11943. submesh.render();
  11944. }
  11945. engine.setAlphaTesting(false);
  11946. // Transparent
  11947. if (this._transparentSubMeshes.length) {
  11948. // Sorting
  11949. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11950. submesh = this._transparentSubMeshes.data[subIndex];
  11951. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11952. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11953. }
  11954. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11955. sortedArray.sort(function (a, b) {
  11956. // Alpha index first
  11957. if (a._alphaIndex > b._alphaIndex) {
  11958. return 1;
  11959. }
  11960. if (a._alphaIndex < b._alphaIndex) {
  11961. return -1;
  11962. }
  11963. // Then distance to camera
  11964. if (a._distanceToCamera < b._distanceToCamera) {
  11965. return 1;
  11966. }
  11967. if (a._distanceToCamera > b._distanceToCamera) {
  11968. return -1;
  11969. }
  11970. return 0;
  11971. });
  11972. // Rendering
  11973. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11974. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11975. submesh = sortedArray[subIndex];
  11976. submesh.render();
  11977. }
  11978. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11979. }
  11980. return true;
  11981. };
  11982. RenderingGroup.prototype.prepare = function () {
  11983. this._opaqueSubMeshes.reset();
  11984. this._transparentSubMeshes.reset();
  11985. this._alphaTestSubMeshes.reset();
  11986. };
  11987. RenderingGroup.prototype.dispatch = function (subMesh) {
  11988. var material = subMesh.getMaterial();
  11989. var mesh = subMesh.getMesh();
  11990. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11991. this._transparentSubMeshes.push(subMesh);
  11992. }
  11993. else if (material.needAlphaTesting()) {
  11994. this._alphaTestSubMeshes.push(subMesh);
  11995. }
  11996. else {
  11997. this._opaqueSubMeshes.push(subMesh); // Opaque
  11998. }
  11999. };
  12000. return RenderingGroup;
  12001. })();
  12002. BABYLON.RenderingGroup = RenderingGroup;
  12003. })(BABYLON || (BABYLON = {}));
  12004. //# sourceMappingURL=babylon.renderingGroup.js.map
  12005. var BABYLON;
  12006. (function (BABYLON) {
  12007. /**
  12008. * Represents a scene to be rendered by the engine.
  12009. * @see http://doc.babylonjs.com/page.php?p=21911
  12010. */
  12011. var Scene = (function () {
  12012. /**
  12013. * @constructor
  12014. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12015. */
  12016. function Scene(engine) {
  12017. // Members
  12018. this.autoClear = true;
  12019. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12020. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12021. this.forceWireframe = false;
  12022. this.forcePointsCloud = false;
  12023. this.forceShowBoundingBoxes = false;
  12024. this.animationsEnabled = true;
  12025. 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
  12026. // Fog
  12027. /**
  12028. * is fog enabled on this scene.
  12029. * @type {boolean}
  12030. */
  12031. this.fogEnabled = true;
  12032. this.fogMode = Scene.FOGMODE_NONE;
  12033. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12034. this.fogDensity = 0.1;
  12035. this.fogStart = 0;
  12036. this.fogEnd = 1000.0;
  12037. // Lights
  12038. /**
  12039. * is shadow enabled on this scene.
  12040. * @type {boolean}
  12041. */
  12042. this.shadowsEnabled = true;
  12043. /**
  12044. * is light enabled on this scene.
  12045. * @type {boolean}
  12046. */
  12047. this.lightsEnabled = true;
  12048. /**
  12049. * All of the lights added to this scene.
  12050. * @see BABYLON.Light
  12051. * @type {BABYLON.Light[]}
  12052. */
  12053. this.lights = new Array();
  12054. // Cameras
  12055. /**
  12056. * All of the cameras added to this scene.
  12057. * @see BABYLON.Camera
  12058. * @type {BABYLON.Camera[]}
  12059. */
  12060. this.cameras = new Array();
  12061. this.activeCameras = new Array();
  12062. // Meshes
  12063. /**
  12064. * All of the (abstract) meshes added to this scene.
  12065. * @see BABYLON.AbstractMesh
  12066. * @type {BABYLON.AbstractMesh[]}
  12067. */
  12068. this.meshes = new Array();
  12069. // Geometries
  12070. this._geometries = new Array();
  12071. this.materials = new Array();
  12072. this.multiMaterials = new Array();
  12073. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12074. // Textures
  12075. this.texturesEnabled = true;
  12076. this.textures = new Array();
  12077. // Particles
  12078. this.particlesEnabled = true;
  12079. this.particleSystems = new Array();
  12080. // Sprites
  12081. this.spritesEnabled = true;
  12082. this.spriteManagers = new Array();
  12083. // Layers
  12084. this.layers = new Array();
  12085. // Skeletons
  12086. this.skeletonsEnabled = true;
  12087. this.skeletons = new Array();
  12088. // Lens flares
  12089. this.lensFlaresEnabled = true;
  12090. this.lensFlareSystems = new Array();
  12091. // Collisions
  12092. this.collisionsEnabled = true;
  12093. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  12094. // Postprocesses
  12095. this.postProcessesEnabled = true;
  12096. // Customs render targets
  12097. this.renderTargetsEnabled = true;
  12098. this.dumpNextRenderTargets = false;
  12099. this.customRenderTargets = new Array();
  12100. // Imported meshes
  12101. this.importedMeshesFiles = new Array();
  12102. this._actionManagers = new Array();
  12103. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12104. // Procedural textures
  12105. this.proceduralTexturesEnabled = true;
  12106. this._proceduralTextures = new Array();
  12107. this.soundTracks = new Array();
  12108. this._audioEnabled = true;
  12109. this._headphone = false;
  12110. this._totalVertices = 0;
  12111. this._activeIndices = 0;
  12112. this._activeParticles = 0;
  12113. this._lastFrameDuration = 0;
  12114. this._evaluateActiveMeshesDuration = 0;
  12115. this._renderTargetsDuration = 0;
  12116. this._particlesDuration = 0;
  12117. this._renderDuration = 0;
  12118. this._spritesDuration = 0;
  12119. this._animationRatio = 0;
  12120. this._renderId = 0;
  12121. this._executeWhenReadyTimeoutId = -1;
  12122. this._toBeDisposed = new BABYLON.SmartArray(256);
  12123. this._onReadyCallbacks = new Array();
  12124. this._pendingData = []; //ANY
  12125. this._onBeforeRenderCallbacks = new Array();
  12126. this._onAfterRenderCallbacks = new Array();
  12127. this._activeMeshes = new BABYLON.SmartArray(256);
  12128. this._processedMaterials = new BABYLON.SmartArray(256);
  12129. this._renderTargets = new BABYLON.SmartArray(256);
  12130. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12131. this._activeSkeletons = new BABYLON.SmartArray(32);
  12132. this._activeBones = 0;
  12133. this._activeAnimatables = new Array();
  12134. this._transformMatrix = BABYLON.Matrix.Zero();
  12135. this._uniqueIdCounter = 0;
  12136. this._engine = engine;
  12137. engine.scenes.push(this);
  12138. this._renderingManager = new BABYLON.RenderingManager(this);
  12139. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12140. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12141. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12142. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12143. this.attachControl();
  12144. this._debugLayer = new BABYLON.DebugLayer(this);
  12145. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12146. //simplification queue
  12147. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12148. //collision coordinator initialization. For now legacy per default.
  12149. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12150. }
  12151. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12152. get: function () {
  12153. return Scene._FOGMODE_NONE;
  12154. },
  12155. enumerable: true,
  12156. configurable: true
  12157. });
  12158. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12159. get: function () {
  12160. return Scene._FOGMODE_EXP;
  12161. },
  12162. enumerable: true,
  12163. configurable: true
  12164. });
  12165. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12166. get: function () {
  12167. return Scene._FOGMODE_EXP2;
  12168. },
  12169. enumerable: true,
  12170. configurable: true
  12171. });
  12172. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12173. get: function () {
  12174. return Scene._FOGMODE_LINEAR;
  12175. },
  12176. enumerable: true,
  12177. configurable: true
  12178. });
  12179. Object.defineProperty(Scene.prototype, "debugLayer", {
  12180. // Properties
  12181. get: function () {
  12182. return this._debugLayer;
  12183. },
  12184. enumerable: true,
  12185. configurable: true
  12186. });
  12187. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12188. get: function () {
  12189. return this._workerCollisions;
  12190. },
  12191. set: function (enabled) {
  12192. enabled = (enabled && !!Worker);
  12193. this._workerCollisions = enabled;
  12194. if (this.collisionCoordinator) {
  12195. this.collisionCoordinator.destroy();
  12196. }
  12197. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12198. this.collisionCoordinator.init(this);
  12199. },
  12200. enumerable: true,
  12201. configurable: true
  12202. });
  12203. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12204. /**
  12205. * The mesh that is currently under the pointer.
  12206. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12207. */
  12208. get: function () {
  12209. return this._meshUnderPointer;
  12210. },
  12211. enumerable: true,
  12212. configurable: true
  12213. });
  12214. Object.defineProperty(Scene.prototype, "pointerX", {
  12215. /**
  12216. * Current on-screen X position of the pointer
  12217. * @return {number} X position of the pointer
  12218. */
  12219. get: function () {
  12220. return this._pointerX;
  12221. },
  12222. enumerable: true,
  12223. configurable: true
  12224. });
  12225. Object.defineProperty(Scene.prototype, "pointerY", {
  12226. /**
  12227. * Current on-screen Y position of the pointer
  12228. * @return {number} Y position of the pointer
  12229. */
  12230. get: function () {
  12231. return this._pointerY;
  12232. },
  12233. enumerable: true,
  12234. configurable: true
  12235. });
  12236. Scene.prototype.getCachedMaterial = function () {
  12237. return this._cachedMaterial;
  12238. };
  12239. Scene.prototype.getBoundingBoxRenderer = function () {
  12240. return this._boundingBoxRenderer;
  12241. };
  12242. Scene.prototype.getOutlineRenderer = function () {
  12243. return this._outlineRenderer;
  12244. };
  12245. Scene.prototype.getEngine = function () {
  12246. return this._engine;
  12247. };
  12248. Scene.prototype.getTotalVertices = function () {
  12249. return this._totalVertices;
  12250. };
  12251. Scene.prototype.getActiveIndices = function () {
  12252. return this._activeIndices;
  12253. };
  12254. Scene.prototype.getActiveParticles = function () {
  12255. return this._activeParticles;
  12256. };
  12257. Scene.prototype.getActiveBones = function () {
  12258. return this._activeBones;
  12259. };
  12260. // Stats
  12261. Scene.prototype.getLastFrameDuration = function () {
  12262. return this._lastFrameDuration;
  12263. };
  12264. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12265. return this._evaluateActiveMeshesDuration;
  12266. };
  12267. Scene.prototype.getActiveMeshes = function () {
  12268. return this._activeMeshes;
  12269. };
  12270. Scene.prototype.getRenderTargetsDuration = function () {
  12271. return this._renderTargetsDuration;
  12272. };
  12273. Scene.prototype.getRenderDuration = function () {
  12274. return this._renderDuration;
  12275. };
  12276. Scene.prototype.getParticlesDuration = function () {
  12277. return this._particlesDuration;
  12278. };
  12279. Scene.prototype.getSpritesDuration = function () {
  12280. return this._spritesDuration;
  12281. };
  12282. Scene.prototype.getAnimationRatio = function () {
  12283. return this._animationRatio;
  12284. };
  12285. Scene.prototype.getRenderId = function () {
  12286. return this._renderId;
  12287. };
  12288. Scene.prototype.incrementRenderId = function () {
  12289. this._renderId++;
  12290. };
  12291. Scene.prototype._updatePointerPosition = function (evt) {
  12292. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12293. this._pointerX = evt.clientX - canvasRect.left;
  12294. this._pointerY = evt.clientY - canvasRect.top;
  12295. if (this.cameraToUseForPointers) {
  12296. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12297. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12298. }
  12299. };
  12300. // Pointers handling
  12301. Scene.prototype.attachControl = function () {
  12302. var _this = this;
  12303. this._onPointerMove = function (evt) {
  12304. var canvas = _this._engine.getRenderingCanvas();
  12305. _this._updatePointerPosition(evt);
  12306. 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);
  12307. if (pickResult.hit) {
  12308. _this._meshUnderPointer = pickResult.pickedMesh;
  12309. _this.setPointerOverMesh(pickResult.pickedMesh);
  12310. canvas.style.cursor = "pointer";
  12311. }
  12312. else {
  12313. _this.setPointerOverMesh(null);
  12314. canvas.style.cursor = "";
  12315. _this._meshUnderPointer = null;
  12316. }
  12317. };
  12318. this._onPointerDown = function (evt) {
  12319. var predicate = null;
  12320. if (!_this.onPointerDown) {
  12321. predicate = function (mesh) {
  12322. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12323. };
  12324. }
  12325. _this._updatePointerPosition(evt);
  12326. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12327. if (pickResult.hit) {
  12328. if (pickResult.pickedMesh.actionManager) {
  12329. switch (evt.button) {
  12330. case 0:
  12331. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12332. break;
  12333. case 1:
  12334. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12335. break;
  12336. case 2:
  12337. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12338. break;
  12339. }
  12340. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12341. }
  12342. }
  12343. if (_this.onPointerDown) {
  12344. _this.onPointerDown(evt, pickResult);
  12345. }
  12346. };
  12347. this._onPointerUp = function (evt) {
  12348. var predicate = null;
  12349. if (!_this.onPointerUp) {
  12350. predicate = function (mesh) {
  12351. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12352. };
  12353. }
  12354. _this._updatePointerPosition(evt);
  12355. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12356. if (pickResult.hit) {
  12357. if (pickResult.pickedMesh.actionManager) {
  12358. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12359. }
  12360. }
  12361. if (_this.onPointerUp) {
  12362. _this.onPointerUp(evt, pickResult);
  12363. }
  12364. };
  12365. this._onKeyDown = function (evt) {
  12366. if (_this.actionManager) {
  12367. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12368. }
  12369. };
  12370. this._onKeyUp = function (evt) {
  12371. if (_this.actionManager) {
  12372. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12373. }
  12374. };
  12375. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12376. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12377. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12378. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12379. BABYLON.Tools.RegisterTopRootEvents([
  12380. { name: "keydown", handler: this._onKeyDown },
  12381. { name: "keyup", handler: this._onKeyUp }
  12382. ]);
  12383. };
  12384. Scene.prototype.detachControl = function () {
  12385. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12386. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12387. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12388. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12389. BABYLON.Tools.UnregisterTopRootEvents([
  12390. { name: "keydown", handler: this._onKeyDown },
  12391. { name: "keyup", handler: this._onKeyUp }
  12392. ]);
  12393. };
  12394. // Ready
  12395. Scene.prototype.isReady = function () {
  12396. if (this._pendingData.length > 0) {
  12397. return false;
  12398. }
  12399. for (var index = 0; index < this._geometries.length; index++) {
  12400. var geometry = this._geometries[index];
  12401. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12402. return false;
  12403. }
  12404. }
  12405. for (index = 0; index < this.meshes.length; index++) {
  12406. var mesh = this.meshes[index];
  12407. if (!mesh.isReady()) {
  12408. return false;
  12409. }
  12410. var mat = mesh.material;
  12411. if (mat) {
  12412. if (!mat.isReady(mesh)) {
  12413. return false;
  12414. }
  12415. }
  12416. }
  12417. return true;
  12418. };
  12419. Scene.prototype.resetCachedMaterial = function () {
  12420. this._cachedMaterial = null;
  12421. };
  12422. Scene.prototype.registerBeforeRender = function (func) {
  12423. this._onBeforeRenderCallbacks.push(func);
  12424. };
  12425. Scene.prototype.unregisterBeforeRender = function (func) {
  12426. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12427. if (index > -1) {
  12428. this._onBeforeRenderCallbacks.splice(index, 1);
  12429. }
  12430. };
  12431. Scene.prototype.registerAfterRender = function (func) {
  12432. this._onAfterRenderCallbacks.push(func);
  12433. };
  12434. Scene.prototype.unregisterAfterRender = function (func) {
  12435. var index = this._onAfterRenderCallbacks.indexOf(func);
  12436. if (index > -1) {
  12437. this._onAfterRenderCallbacks.splice(index, 1);
  12438. }
  12439. };
  12440. Scene.prototype._addPendingData = function (data) {
  12441. this._pendingData.push(data);
  12442. };
  12443. Scene.prototype._removePendingData = function (data) {
  12444. var index = this._pendingData.indexOf(data);
  12445. if (index !== -1) {
  12446. this._pendingData.splice(index, 1);
  12447. }
  12448. };
  12449. Scene.prototype.getWaitingItemsCount = function () {
  12450. return this._pendingData.length;
  12451. };
  12452. /**
  12453. * Registers a function to be executed when the scene is ready.
  12454. * @param {Function} func - the function to be executed.
  12455. */
  12456. Scene.prototype.executeWhenReady = function (func) {
  12457. var _this = this;
  12458. this._onReadyCallbacks.push(func);
  12459. if (this._executeWhenReadyTimeoutId !== -1) {
  12460. return;
  12461. }
  12462. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12463. _this._checkIsReady();
  12464. }, 150);
  12465. };
  12466. Scene.prototype._checkIsReady = function () {
  12467. var _this = this;
  12468. if (this.isReady()) {
  12469. this._onReadyCallbacks.forEach(function (func) {
  12470. func();
  12471. });
  12472. this._onReadyCallbacks = [];
  12473. this._executeWhenReadyTimeoutId = -1;
  12474. return;
  12475. }
  12476. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12477. _this._checkIsReady();
  12478. }, 150);
  12479. };
  12480. // Animations
  12481. /**
  12482. * Will start the animation sequence of a given target
  12483. * @param target - the target
  12484. * @param {number} from - from which frame should animation start
  12485. * @param {number} to - till which frame should animation run.
  12486. * @param {boolean} [loop] - should the animation loop
  12487. * @param {number} [speedRatio] - the speed in which to run the animation
  12488. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12489. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12490. * @return {BABYLON.Animatable} the animatable object created for this animation
  12491. * @see BABYLON.Animatable
  12492. * @see http://doc.babylonjs.com/page.php?p=22081
  12493. */
  12494. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12495. if (speedRatio === undefined) {
  12496. speedRatio = 1.0;
  12497. }
  12498. this.stopAnimation(target);
  12499. if (!animatable) {
  12500. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12501. }
  12502. // Local animations
  12503. if (target.animations) {
  12504. animatable.appendAnimations(target, target.animations);
  12505. }
  12506. // Children animations
  12507. if (target.getAnimatables) {
  12508. var animatables = target.getAnimatables();
  12509. for (var index = 0; index < animatables.length; index++) {
  12510. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12511. }
  12512. }
  12513. return animatable;
  12514. };
  12515. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12516. if (speedRatio === undefined) {
  12517. speedRatio = 1.0;
  12518. }
  12519. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12520. return animatable;
  12521. };
  12522. Scene.prototype.getAnimatableByTarget = function (target) {
  12523. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12524. if (this._activeAnimatables[index].target === target) {
  12525. return this._activeAnimatables[index];
  12526. }
  12527. }
  12528. return null;
  12529. };
  12530. /**
  12531. * Will stop the animation of the given target
  12532. * @param target - the target
  12533. * @see beginAnimation
  12534. */
  12535. Scene.prototype.stopAnimation = function (target) {
  12536. var animatable = this.getAnimatableByTarget(target);
  12537. if (animatable) {
  12538. animatable.stop();
  12539. }
  12540. };
  12541. Scene.prototype._animate = function () {
  12542. if (!this.animationsEnabled) {
  12543. return;
  12544. }
  12545. if (!this._animationStartDate) {
  12546. this._animationStartDate = BABYLON.Tools.Now;
  12547. }
  12548. // Getting time
  12549. var now = BABYLON.Tools.Now;
  12550. var delay = now - this._animationStartDate;
  12551. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12552. this._activeAnimatables[index]._animate(delay);
  12553. }
  12554. };
  12555. // Matrix
  12556. Scene.prototype.getViewMatrix = function () {
  12557. return this._viewMatrix;
  12558. };
  12559. Scene.prototype.getProjectionMatrix = function () {
  12560. return this._projectionMatrix;
  12561. };
  12562. Scene.prototype.getTransformMatrix = function () {
  12563. return this._transformMatrix;
  12564. };
  12565. Scene.prototype.setTransformMatrix = function (view, projection) {
  12566. this._viewMatrix = view;
  12567. this._projectionMatrix = projection;
  12568. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12569. };
  12570. // Methods
  12571. Scene.prototype.addMesh = function (newMesh) {
  12572. newMesh.uniqueId = this._uniqueIdCounter++;
  12573. var position = this.meshes.push(newMesh);
  12574. //notify the collision coordinator
  12575. this.collisionCoordinator.onMeshAdded(newMesh);
  12576. if (this.onNewMeshAdded) {
  12577. this.onNewMeshAdded(newMesh, position, this);
  12578. }
  12579. };
  12580. Scene.prototype.removeMesh = function (toRemove) {
  12581. var index = this.meshes.indexOf(toRemove);
  12582. if (index !== -1) {
  12583. // Remove from the scene if mesh found
  12584. this.meshes.splice(index, 1);
  12585. }
  12586. //notify the collision coordinator
  12587. this.collisionCoordinator.onMeshRemoved(toRemove);
  12588. if (this.onMeshRemoved) {
  12589. this.onMeshRemoved(toRemove);
  12590. }
  12591. return index;
  12592. };
  12593. Scene.prototype.removeLight = function (toRemove) {
  12594. var index = this.lights.indexOf(toRemove);
  12595. if (index !== -1) {
  12596. // Remove from the scene if mesh found
  12597. this.lights.splice(index, 1);
  12598. }
  12599. if (this.onLightRemoved) {
  12600. this.onLightRemoved(toRemove);
  12601. }
  12602. return index;
  12603. };
  12604. Scene.prototype.removeCamera = function (toRemove) {
  12605. var index = this.cameras.indexOf(toRemove);
  12606. if (index !== -1) {
  12607. // Remove from the scene if mesh found
  12608. this.cameras.splice(index, 1);
  12609. }
  12610. // Remove from activeCameras
  12611. var index2 = this.activeCameras.indexOf(toRemove);
  12612. if (index2 !== -1) {
  12613. // Remove from the scene if mesh found
  12614. this.activeCameras.splice(index2, 1);
  12615. }
  12616. // Reset the activeCamera
  12617. if (this.activeCamera === toRemove) {
  12618. if (this.cameras.length > 0) {
  12619. this.activeCamera = this.cameras[0];
  12620. }
  12621. else {
  12622. this.activeCamera = null;
  12623. }
  12624. }
  12625. if (this.onCameraRemoved) {
  12626. this.onCameraRemoved(toRemove);
  12627. }
  12628. return index;
  12629. };
  12630. Scene.prototype.addLight = function (newLight) {
  12631. newLight.uniqueId = this._uniqueIdCounter++;
  12632. var position = this.lights.push(newLight);
  12633. if (this.onNewLightAdded) {
  12634. this.onNewLightAdded(newLight, position, this);
  12635. }
  12636. };
  12637. Scene.prototype.addCamera = function (newCamera) {
  12638. newCamera.uniqueId = this._uniqueIdCounter++;
  12639. var position = this.cameras.push(newCamera);
  12640. if (this.onNewCameraAdded) {
  12641. this.onNewCameraAdded(newCamera, position, this);
  12642. }
  12643. };
  12644. /**
  12645. * sets the active camera of the scene using its ID
  12646. * @param {string} id - the camera's ID
  12647. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12648. * @see activeCamera
  12649. */
  12650. Scene.prototype.setActiveCameraByID = function (id) {
  12651. var camera = this.getCameraByID(id);
  12652. if (camera) {
  12653. this.activeCamera = camera;
  12654. return camera;
  12655. }
  12656. return null;
  12657. };
  12658. /**
  12659. * sets the active camera of the scene using its name
  12660. * @param {string} name - the camera's name
  12661. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12662. * @see activeCamera
  12663. */
  12664. Scene.prototype.setActiveCameraByName = function (name) {
  12665. var camera = this.getCameraByName(name);
  12666. if (camera) {
  12667. this.activeCamera = camera;
  12668. return camera;
  12669. }
  12670. return null;
  12671. };
  12672. /**
  12673. * get a material using its id
  12674. * @param {string} the material's ID
  12675. * @return {BABYLON.Material|null} the material or null if none found.
  12676. */
  12677. Scene.prototype.getMaterialByID = function (id) {
  12678. for (var index = 0; index < this.materials.length; index++) {
  12679. if (this.materials[index].id === id) {
  12680. return this.materials[index];
  12681. }
  12682. }
  12683. return null;
  12684. };
  12685. /**
  12686. * get a material using its name
  12687. * @param {string} the material's name
  12688. * @return {BABYLON.Material|null} the material or null if none found.
  12689. */
  12690. Scene.prototype.getMaterialByName = function (name) {
  12691. for (var index = 0; index < this.materials.length; index++) {
  12692. if (this.materials[index].name === name) {
  12693. return this.materials[index];
  12694. }
  12695. }
  12696. return null;
  12697. };
  12698. Scene.prototype.getCameraByID = function (id) {
  12699. for (var index = 0; index < this.cameras.length; index++) {
  12700. if (this.cameras[index].id === id) {
  12701. return this.cameras[index];
  12702. }
  12703. }
  12704. return null;
  12705. };
  12706. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12707. for (var index = 0; index < this.cameras.length; index++) {
  12708. if (this.cameras[index].uniqueId === uniqueId) {
  12709. return this.cameras[index];
  12710. }
  12711. }
  12712. return null;
  12713. };
  12714. /**
  12715. * get a camera using its name
  12716. * @param {string} the camera's name
  12717. * @return {BABYLON.Camera|null} the camera or null if none found.
  12718. */
  12719. Scene.prototype.getCameraByName = function (name) {
  12720. for (var index = 0; index < this.cameras.length; index++) {
  12721. if (this.cameras[index].name === name) {
  12722. return this.cameras[index];
  12723. }
  12724. }
  12725. return null;
  12726. };
  12727. /**
  12728. * get a light node using its name
  12729. * @param {string} the light's name
  12730. * @return {BABYLON.Light|null} the light or null if none found.
  12731. */
  12732. Scene.prototype.getLightByName = function (name) {
  12733. for (var index = 0; index < this.lights.length; index++) {
  12734. if (this.lights[index].name === name) {
  12735. return this.lights[index];
  12736. }
  12737. }
  12738. return null;
  12739. };
  12740. /**
  12741. * get a light node using its ID
  12742. * @param {string} the light's id
  12743. * @return {BABYLON.Light|null} the light or null if none found.
  12744. */
  12745. Scene.prototype.getLightByID = function (id) {
  12746. for (var index = 0; index < this.lights.length; index++) {
  12747. if (this.lights[index].id === id) {
  12748. return this.lights[index];
  12749. }
  12750. }
  12751. return null;
  12752. };
  12753. /**
  12754. * get a light node using its scene-generated unique ID
  12755. * @param {number} the light's unique id
  12756. * @return {BABYLON.Light|null} the light or null if none found.
  12757. */
  12758. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12759. for (var index = 0; index < this.lights.length; index++) {
  12760. if (this.lights[index].uniqueId === uniqueId) {
  12761. return this.lights[index];
  12762. }
  12763. }
  12764. return null;
  12765. };
  12766. /**
  12767. * get a geometry using its ID
  12768. * @param {string} the geometry's id
  12769. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12770. */
  12771. Scene.prototype.getGeometryByID = function (id) {
  12772. for (var index = 0; index < this._geometries.length; index++) {
  12773. if (this._geometries[index].id === id) {
  12774. return this._geometries[index];
  12775. }
  12776. }
  12777. return null;
  12778. };
  12779. /**
  12780. * add a new geometry to this scene.
  12781. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12782. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12783. * @return {boolean} was the geometry added or not
  12784. */
  12785. Scene.prototype.pushGeometry = function (geometry, force) {
  12786. if (!force && this.getGeometryByID(geometry.id)) {
  12787. return false;
  12788. }
  12789. this._geometries.push(geometry);
  12790. //notify the collision coordinator
  12791. this.collisionCoordinator.onGeometryAdded(geometry);
  12792. if (this.onGeometryAdded) {
  12793. this.onGeometryAdded(geometry);
  12794. }
  12795. return true;
  12796. };
  12797. /**
  12798. * Removes an existing geometry
  12799. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12800. * @return {boolean} was the geometry removed or not
  12801. */
  12802. Scene.prototype.removeGeometry = function (geometry) {
  12803. var index = this._geometries.indexOf(geometry);
  12804. if (index > -1) {
  12805. this._geometries.splice(index, 1);
  12806. //notify the collision coordinator
  12807. this.collisionCoordinator.onGeometryDeleted(geometry);
  12808. if (this.onGeometryRemoved) {
  12809. this.onGeometryRemoved(geometry);
  12810. }
  12811. return true;
  12812. }
  12813. return false;
  12814. };
  12815. Scene.prototype.getGeometries = function () {
  12816. return this._geometries;
  12817. };
  12818. /**
  12819. * Get the first added mesh found of a given ID
  12820. * @param {string} id - the id to search for
  12821. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12822. */
  12823. Scene.prototype.getMeshByID = function (id) {
  12824. for (var index = 0; index < this.meshes.length; index++) {
  12825. if (this.meshes[index].id === id) {
  12826. return this.meshes[index];
  12827. }
  12828. }
  12829. return null;
  12830. };
  12831. /**
  12832. * Get a mesh with its auto-generated unique id
  12833. * @param {number} uniqueId - the unique id to search for
  12834. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12835. */
  12836. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12837. for (var index = 0; index < this.meshes.length; index++) {
  12838. if (this.meshes[index].uniqueId === uniqueId) {
  12839. return this.meshes[index];
  12840. }
  12841. }
  12842. return null;
  12843. };
  12844. /**
  12845. * Get a the last added mesh found of a given ID
  12846. * @param {string} id - the id to search for
  12847. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12848. */
  12849. Scene.prototype.getLastMeshByID = function (id) {
  12850. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12851. if (this.meshes[index].id === id) {
  12852. return this.meshes[index];
  12853. }
  12854. }
  12855. return null;
  12856. };
  12857. /**
  12858. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12859. * @param {string} id - the id to search for
  12860. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12861. */
  12862. Scene.prototype.getLastEntryByID = function (id) {
  12863. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12864. if (this.meshes[index].id === id) {
  12865. return this.meshes[index];
  12866. }
  12867. }
  12868. for (index = this.cameras.length - 1; index >= 0; index--) {
  12869. if (this.cameras[index].id === id) {
  12870. return this.cameras[index];
  12871. }
  12872. }
  12873. for (index = this.lights.length - 1; index >= 0; index--) {
  12874. if (this.lights[index].id === id) {
  12875. return this.lights[index];
  12876. }
  12877. }
  12878. return null;
  12879. };
  12880. Scene.prototype.getNodeByName = function (name) {
  12881. var mesh = this.getMeshByName(name);
  12882. if (mesh) {
  12883. return mesh;
  12884. }
  12885. var light = this.getLightByName(name);
  12886. if (light) {
  12887. return light;
  12888. }
  12889. return this.getCameraByName(name);
  12890. };
  12891. Scene.prototype.getMeshByName = function (name) {
  12892. for (var index = 0; index < this.meshes.length; index++) {
  12893. if (this.meshes[index].name === name) {
  12894. return this.meshes[index];
  12895. }
  12896. }
  12897. return null;
  12898. };
  12899. Scene.prototype.getSoundByName = function (name) {
  12900. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12901. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12902. return this.mainSoundTrack.soundCollection[index];
  12903. }
  12904. }
  12905. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12906. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12907. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12908. return this.soundTracks[sdIndex].soundCollection[index];
  12909. }
  12910. }
  12911. }
  12912. return null;
  12913. };
  12914. Scene.prototype.getLastSkeletonByID = function (id) {
  12915. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12916. if (this.skeletons[index].id === id) {
  12917. return this.skeletons[index];
  12918. }
  12919. }
  12920. return null;
  12921. };
  12922. Scene.prototype.getSkeletonById = function (id) {
  12923. for (var index = 0; index < this.skeletons.length; index++) {
  12924. if (this.skeletons[index].id === id) {
  12925. return this.skeletons[index];
  12926. }
  12927. }
  12928. return null;
  12929. };
  12930. Scene.prototype.getSkeletonByName = function (name) {
  12931. for (var index = 0; index < this.skeletons.length; index++) {
  12932. if (this.skeletons[index].name === name) {
  12933. return this.skeletons[index];
  12934. }
  12935. }
  12936. return null;
  12937. };
  12938. Scene.prototype.isActiveMesh = function (mesh) {
  12939. return (this._activeMeshes.indexOf(mesh) !== -1);
  12940. };
  12941. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12942. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12943. var material = subMesh.getMaterial();
  12944. if (mesh.showSubMeshesBoundingBox) {
  12945. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12946. }
  12947. if (material) {
  12948. // Render targets
  12949. if (material.getRenderTargetTextures) {
  12950. if (this._processedMaterials.indexOf(material) === -1) {
  12951. this._processedMaterials.push(material);
  12952. this._renderTargets.concat(material.getRenderTargetTextures());
  12953. }
  12954. }
  12955. // Dispatch
  12956. this._activeIndices += subMesh.indexCount;
  12957. this._renderingManager.dispatch(subMesh);
  12958. }
  12959. }
  12960. };
  12961. Scene.prototype._evaluateActiveMeshes = function () {
  12962. this.activeCamera._activeMeshes.reset();
  12963. this._activeMeshes.reset();
  12964. this._renderingManager.reset();
  12965. this._processedMaterials.reset();
  12966. this._activeParticleSystems.reset();
  12967. this._activeSkeletons.reset();
  12968. this._boundingBoxRenderer.reset();
  12969. if (!this._frustumPlanes) {
  12970. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12971. }
  12972. else {
  12973. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12974. }
  12975. // Meshes
  12976. var meshes;
  12977. var len;
  12978. if (this._selectionOctree) {
  12979. var selection = this._selectionOctree.select(this._frustumPlanes);
  12980. meshes = selection.data;
  12981. len = selection.length;
  12982. }
  12983. else {
  12984. len = this.meshes.length;
  12985. meshes = this.meshes;
  12986. }
  12987. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12988. var mesh = meshes[meshIndex];
  12989. if (mesh.isBlocked) {
  12990. continue;
  12991. }
  12992. this._totalVertices += mesh.getTotalVertices();
  12993. if (!mesh.isReady() || !mesh.isEnabled()) {
  12994. continue;
  12995. }
  12996. mesh.computeWorldMatrix();
  12997. // Intersections
  12998. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12999. this._meshesForIntersections.pushNoDuplicate(mesh);
  13000. }
  13001. // Switch to current LOD
  13002. var meshLOD = mesh.getLOD(this.activeCamera);
  13003. if (!meshLOD) {
  13004. continue;
  13005. }
  13006. mesh._preActivate();
  13007. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13008. this._activeMeshes.push(mesh);
  13009. this.activeCamera._activeMeshes.push(mesh);
  13010. mesh._activate(this._renderId);
  13011. this._activeMesh(meshLOD);
  13012. }
  13013. }
  13014. // Particle systems
  13015. var beforeParticlesDate = BABYLON.Tools.Now;
  13016. if (this.particlesEnabled) {
  13017. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13018. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13019. var particleSystem = this.particleSystems[particleIndex];
  13020. if (!particleSystem.isStarted()) {
  13021. continue;
  13022. }
  13023. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13024. this._activeParticleSystems.push(particleSystem);
  13025. particleSystem.animate();
  13026. }
  13027. }
  13028. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13029. }
  13030. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13031. };
  13032. Scene.prototype._activeMesh = function (mesh) {
  13033. if (mesh.skeleton && this.skeletonsEnabled) {
  13034. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13035. }
  13036. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13037. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13038. }
  13039. if (mesh && mesh.subMeshes) {
  13040. // Submeshes Octrees
  13041. var len;
  13042. var subMeshes;
  13043. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13044. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13045. len = intersections.length;
  13046. subMeshes = intersections.data;
  13047. }
  13048. else {
  13049. subMeshes = mesh.subMeshes;
  13050. len = subMeshes.length;
  13051. }
  13052. for (var subIndex = 0; subIndex < len; subIndex++) {
  13053. var subMesh = subMeshes[subIndex];
  13054. this._evaluateSubMesh(subMesh, mesh);
  13055. }
  13056. }
  13057. };
  13058. Scene.prototype.updateTransformMatrix = function (force) {
  13059. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13060. };
  13061. Scene.prototype._renderForCamera = function (camera) {
  13062. var engine = this._engine;
  13063. this.activeCamera = camera;
  13064. if (!this.activeCamera)
  13065. throw new Error("Active camera not set");
  13066. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13067. // Viewport
  13068. engine.setViewport(this.activeCamera.viewport);
  13069. // Camera
  13070. this.resetCachedMaterial();
  13071. this._renderId++;
  13072. this.updateTransformMatrix();
  13073. if (this.beforeCameraRender) {
  13074. this.beforeCameraRender(this.activeCamera);
  13075. }
  13076. // Meshes
  13077. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13078. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13079. this._evaluateActiveMeshes();
  13080. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13081. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13082. // Skeletons
  13083. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13084. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13085. skeleton.prepare();
  13086. }
  13087. // Render targets
  13088. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13089. if (this.renderTargetsEnabled) {
  13090. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13091. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13092. var renderTarget = this._renderTargets.data[renderIndex];
  13093. if (renderTarget._shouldRender()) {
  13094. this._renderId++;
  13095. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13096. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13097. }
  13098. }
  13099. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13100. this._renderId++;
  13101. }
  13102. if (this._renderTargets.length > 0) {
  13103. engine.restoreDefaultFramebuffer();
  13104. }
  13105. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13106. // Prepare Frame
  13107. this.postProcessManager._prepareFrame();
  13108. var beforeRenderDate = BABYLON.Tools.Now;
  13109. // Backgrounds
  13110. if (this.layers.length) {
  13111. engine.setDepthBuffer(false);
  13112. var layerIndex;
  13113. var layer;
  13114. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13115. layer = this.layers[layerIndex];
  13116. if (layer.isBackground) {
  13117. layer.render();
  13118. }
  13119. }
  13120. engine.setDepthBuffer(true);
  13121. }
  13122. // Render
  13123. BABYLON.Tools.StartPerformanceCounter("Main render");
  13124. this._renderingManager.render(null, null, true, true);
  13125. BABYLON.Tools.EndPerformanceCounter("Main render");
  13126. // Bounding boxes
  13127. this._boundingBoxRenderer.render();
  13128. // Lens flares
  13129. if (this.lensFlaresEnabled) {
  13130. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13131. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13132. this.lensFlareSystems[lensFlareSystemIndex].render();
  13133. }
  13134. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13135. }
  13136. // Foregrounds
  13137. if (this.layers.length) {
  13138. engine.setDepthBuffer(false);
  13139. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13140. layer = this.layers[layerIndex];
  13141. if (!layer.isBackground) {
  13142. layer.render();
  13143. }
  13144. }
  13145. engine.setDepthBuffer(true);
  13146. }
  13147. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13148. // Finalize frame
  13149. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13150. // Update camera
  13151. this.activeCamera._updateFromScene();
  13152. // Reset some special arrays
  13153. this._renderTargets.reset();
  13154. if (this.afterCameraRender) {
  13155. this.afterCameraRender(this.activeCamera);
  13156. }
  13157. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13158. };
  13159. Scene.prototype._processSubCameras = function (camera) {
  13160. if (camera.subCameras.length === 0) {
  13161. this._renderForCamera(camera);
  13162. return;
  13163. }
  13164. // Sub-cameras
  13165. for (var index = 0; index < camera.subCameras.length; index++) {
  13166. this._renderForCamera(camera.subCameras[index]);
  13167. }
  13168. this.activeCamera = camera;
  13169. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13170. // Update camera
  13171. this.activeCamera._updateFromScene();
  13172. };
  13173. Scene.prototype._checkIntersections = function () {
  13174. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13175. var sourceMesh = this._meshesForIntersections.data[index];
  13176. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13177. var action = sourceMesh.actionManager.actions[actionIndex];
  13178. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13179. var parameters = action.getTriggerParameter();
  13180. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13181. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13182. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13183. if (areIntersecting && currentIntersectionInProgress === -1) {
  13184. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13185. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13186. sourceMesh._intersectionsInProgress.push(otherMesh);
  13187. }
  13188. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13189. sourceMesh._intersectionsInProgress.push(otherMesh);
  13190. }
  13191. }
  13192. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13193. //They intersected, and now they don't.
  13194. //is this trigger an exit trigger? execute an event.
  13195. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13196. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13197. }
  13198. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13199. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13200. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13201. }
  13202. }
  13203. }
  13204. }
  13205. }
  13206. };
  13207. Scene.prototype.render = function () {
  13208. var startDate = BABYLON.Tools.Now;
  13209. this._particlesDuration = 0;
  13210. this._spritesDuration = 0;
  13211. this._activeParticles = 0;
  13212. this._renderDuration = 0;
  13213. this._renderTargetsDuration = 0;
  13214. this._evaluateActiveMeshesDuration = 0;
  13215. this._totalVertices = 0;
  13216. this._activeIndices = 0;
  13217. this._activeBones = 0;
  13218. this.getEngine().resetDrawCalls();
  13219. this._meshesForIntersections.reset();
  13220. this.resetCachedMaterial();
  13221. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13222. // Actions
  13223. if (this.actionManager) {
  13224. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13225. }
  13226. //Simplification Queue
  13227. if (!this.simplificationQueue.running) {
  13228. this.simplificationQueue.executeNext();
  13229. }
  13230. // Before render
  13231. if (this.beforeRender) {
  13232. this.beforeRender();
  13233. }
  13234. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13235. this._onBeforeRenderCallbacks[callbackIndex]();
  13236. }
  13237. // Animations
  13238. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13239. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13240. this._animate();
  13241. // Physics
  13242. if (this._physicsEngine) {
  13243. BABYLON.Tools.StartPerformanceCounter("Physics");
  13244. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13245. BABYLON.Tools.EndPerformanceCounter("Physics");
  13246. }
  13247. // Customs render targets
  13248. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13249. var engine = this.getEngine();
  13250. var currentActiveCamera = this.activeCamera;
  13251. if (this.renderTargetsEnabled) {
  13252. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13253. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13254. var renderTarget = this.customRenderTargets[customIndex];
  13255. if (renderTarget._shouldRender()) {
  13256. this._renderId++;
  13257. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13258. if (!this.activeCamera)
  13259. throw new Error("Active camera not set");
  13260. // Viewport
  13261. engine.setViewport(this.activeCamera.viewport);
  13262. // Camera
  13263. this.updateTransformMatrix();
  13264. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13265. }
  13266. }
  13267. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13268. this._renderId++;
  13269. }
  13270. if (this.customRenderTargets.length > 0) {
  13271. engine.restoreDefaultFramebuffer();
  13272. }
  13273. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13274. this.activeCamera = currentActiveCamera;
  13275. // Procedural textures
  13276. if (this.proceduralTexturesEnabled) {
  13277. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13278. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13279. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13280. if (proceduralTexture._shouldRender()) {
  13281. proceduralTexture.render();
  13282. }
  13283. }
  13284. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13285. }
  13286. // Clear
  13287. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13288. // Shadows
  13289. if (this.shadowsEnabled) {
  13290. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13291. var light = this.lights[lightIndex];
  13292. var shadowGenerator = light.getShadowGenerator();
  13293. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13294. this._renderTargets.push(shadowGenerator.getShadowMap());
  13295. }
  13296. }
  13297. }
  13298. // Depth renderer
  13299. if (this._depthRenderer) {
  13300. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13301. }
  13302. // RenderPipeline
  13303. this.postProcessRenderPipelineManager.update();
  13304. // Multi-cameras?
  13305. if (this.activeCameras.length > 0) {
  13306. var currentRenderId = this._renderId;
  13307. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13308. this._renderId = currentRenderId;
  13309. this._processSubCameras(this.activeCameras[cameraIndex]);
  13310. }
  13311. }
  13312. else {
  13313. if (!this.activeCamera) {
  13314. throw new Error("No camera defined");
  13315. }
  13316. this._processSubCameras(this.activeCamera);
  13317. }
  13318. // Intersection checks
  13319. this._checkIntersections();
  13320. // Update the audio listener attached to the camera
  13321. this._updateAudioParameters();
  13322. // After render
  13323. if (this.afterRender) {
  13324. this.afterRender();
  13325. }
  13326. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13327. this._onAfterRenderCallbacks[callbackIndex]();
  13328. }
  13329. // Cleaning
  13330. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13331. this._toBeDisposed.data[index].dispose();
  13332. this._toBeDisposed[index] = null;
  13333. }
  13334. this._toBeDisposed.reset();
  13335. if (this.dumpNextRenderTargets) {
  13336. this.dumpNextRenderTargets = false;
  13337. }
  13338. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13339. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13340. };
  13341. Scene.prototype._updateAudioParameters = function () {
  13342. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13343. return;
  13344. }
  13345. var listeningCamera;
  13346. var audioEngine = BABYLON.Engine.audioEngine;
  13347. if (this.activeCameras.length > 0) {
  13348. listeningCamera = this.activeCameras[0];
  13349. }
  13350. else {
  13351. listeningCamera = this.activeCamera;
  13352. }
  13353. if (listeningCamera && audioEngine.canUseWebAudio) {
  13354. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13355. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13356. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13357. cameraDirection.normalize();
  13358. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13359. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13360. var sound = this.mainSoundTrack.soundCollection[i];
  13361. if (sound.useCustomAttenuation) {
  13362. sound.updateDistanceFromListener();
  13363. }
  13364. }
  13365. for (i = 0; i < this.soundTracks.length; i++) {
  13366. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13367. sound = this.soundTracks[i].soundCollection[j];
  13368. if (sound.useCustomAttenuation) {
  13369. sound.updateDistanceFromListener();
  13370. }
  13371. }
  13372. }
  13373. }
  13374. };
  13375. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13376. // Audio
  13377. get: function () {
  13378. return this._audioEnabled;
  13379. },
  13380. set: function (value) {
  13381. this._audioEnabled = value;
  13382. if (this._audioEnabled) {
  13383. this._enableAudio();
  13384. }
  13385. else {
  13386. this._disableAudio();
  13387. }
  13388. },
  13389. enumerable: true,
  13390. configurable: true
  13391. });
  13392. Scene.prototype._disableAudio = function () {
  13393. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13394. this.mainSoundTrack.soundCollection[i].pause();
  13395. }
  13396. for (i = 0; i < this.soundTracks.length; i++) {
  13397. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13398. this.soundTracks[i].soundCollection[j].pause();
  13399. }
  13400. }
  13401. };
  13402. Scene.prototype._enableAudio = function () {
  13403. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13404. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13405. this.mainSoundTrack.soundCollection[i].play();
  13406. }
  13407. }
  13408. for (i = 0; i < this.soundTracks.length; i++) {
  13409. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13410. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13411. this.soundTracks[i].soundCollection[j].play();
  13412. }
  13413. }
  13414. }
  13415. };
  13416. Object.defineProperty(Scene.prototype, "headphone", {
  13417. get: function () {
  13418. return this._headphone;
  13419. },
  13420. set: function (value) {
  13421. this._headphone = value;
  13422. if (this._headphone) {
  13423. this._switchAudioModeForHeadphones();
  13424. }
  13425. else {
  13426. this._switchAudioModeForNormalSpeakers();
  13427. }
  13428. },
  13429. enumerable: true,
  13430. configurable: true
  13431. });
  13432. Scene.prototype._switchAudioModeForHeadphones = function () {
  13433. this.mainSoundTrack.switchPanningModelToHRTF();
  13434. for (var i = 0; i < this.soundTracks.length; i++) {
  13435. this.soundTracks[i].switchPanningModelToHRTF();
  13436. }
  13437. };
  13438. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13439. this.mainSoundTrack.switchPanningModelToEqualPower();
  13440. for (var i = 0; i < this.soundTracks.length; i++) {
  13441. this.soundTracks[i].switchPanningModelToEqualPower();
  13442. }
  13443. };
  13444. Scene.prototype.enableDepthRenderer = function () {
  13445. if (this._depthRenderer) {
  13446. return this._depthRenderer;
  13447. }
  13448. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13449. return this._depthRenderer;
  13450. };
  13451. Scene.prototype.disableDepthRenderer = function () {
  13452. if (!this._depthRenderer) {
  13453. return;
  13454. }
  13455. this._depthRenderer.dispose();
  13456. this._depthRenderer = null;
  13457. };
  13458. Scene.prototype.dispose = function () {
  13459. this.beforeRender = null;
  13460. this.afterRender = null;
  13461. this.skeletons = [];
  13462. this._boundingBoxRenderer.dispose();
  13463. if (this._depthRenderer) {
  13464. this._depthRenderer.dispose();
  13465. }
  13466. // Debug layer
  13467. this.debugLayer.hide();
  13468. // Events
  13469. if (this.onDispose) {
  13470. this.onDispose();
  13471. }
  13472. this._onBeforeRenderCallbacks = [];
  13473. this._onAfterRenderCallbacks = [];
  13474. this.detachControl();
  13475. // Release sounds & sounds tracks
  13476. this.disposeSounds();
  13477. // Detach cameras
  13478. var canvas = this._engine.getRenderingCanvas();
  13479. var index;
  13480. for (index = 0; index < this.cameras.length; index++) {
  13481. this.cameras[index].detachControl(canvas);
  13482. }
  13483. // Release lights
  13484. while (this.lights.length) {
  13485. this.lights[0].dispose();
  13486. }
  13487. // Release meshes
  13488. while (this.meshes.length) {
  13489. this.meshes[0].dispose(true);
  13490. }
  13491. // Release cameras
  13492. while (this.cameras.length) {
  13493. this.cameras[0].dispose();
  13494. }
  13495. // Release materials
  13496. while (this.materials.length) {
  13497. this.materials[0].dispose();
  13498. }
  13499. // Release particles
  13500. while (this.particleSystems.length) {
  13501. this.particleSystems[0].dispose();
  13502. }
  13503. // Release sprites
  13504. while (this.spriteManagers.length) {
  13505. this.spriteManagers[0].dispose();
  13506. }
  13507. // Release layers
  13508. while (this.layers.length) {
  13509. this.layers[0].dispose();
  13510. }
  13511. // Release textures
  13512. while (this.textures.length) {
  13513. this.textures[0].dispose();
  13514. }
  13515. // Post-processes
  13516. this.postProcessManager.dispose();
  13517. // Physics
  13518. if (this._physicsEngine) {
  13519. this.disablePhysicsEngine();
  13520. }
  13521. // Remove from engine
  13522. index = this._engine.scenes.indexOf(this);
  13523. if (index > -1) {
  13524. this._engine.scenes.splice(index, 1);
  13525. }
  13526. this._engine.wipeCaches();
  13527. };
  13528. // Release sounds & sounds tracks
  13529. Scene.prototype.disposeSounds = function () {
  13530. this.mainSoundTrack.dispose();
  13531. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13532. this.soundTracks[scIndex].dispose();
  13533. }
  13534. };
  13535. // Octrees
  13536. Scene.prototype.getWorldExtends = function () {
  13537. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13538. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13539. for (var index = 0; index < this.meshes.length; index++) {
  13540. var mesh = this.meshes[index];
  13541. mesh.computeWorldMatrix(true);
  13542. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13543. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13544. BABYLON.Tools.CheckExtends(minBox, min, max);
  13545. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13546. }
  13547. return {
  13548. min: min,
  13549. max: max
  13550. };
  13551. };
  13552. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13553. if (maxCapacity === void 0) { maxCapacity = 64; }
  13554. if (maxDepth === void 0) { maxDepth = 2; }
  13555. if (!this._selectionOctree) {
  13556. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13557. }
  13558. var worldExtends = this.getWorldExtends();
  13559. // Update octree
  13560. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13561. return this._selectionOctree;
  13562. };
  13563. // Picking
  13564. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13565. var engine = this._engine;
  13566. if (!camera) {
  13567. if (!this.activeCamera)
  13568. throw new Error("Active camera not set");
  13569. camera = this.activeCamera;
  13570. }
  13571. var cameraViewport = camera.viewport;
  13572. var viewport = cameraViewport.toGlobal(engine);
  13573. // Moving coordinates to local viewport world
  13574. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13575. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13576. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13577. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13578. };
  13579. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13580. var pickingInfo = null;
  13581. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13582. var mesh = this.meshes[meshIndex];
  13583. if (predicate) {
  13584. if (!predicate(mesh)) {
  13585. continue;
  13586. }
  13587. }
  13588. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13589. continue;
  13590. }
  13591. var world = mesh.getWorldMatrix();
  13592. var ray = rayFunction(world);
  13593. var result = mesh.intersects(ray, fastCheck);
  13594. if (!result || !result.hit)
  13595. continue;
  13596. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13597. continue;
  13598. pickingInfo = result;
  13599. if (fastCheck) {
  13600. break;
  13601. }
  13602. }
  13603. return pickingInfo || new BABYLON.PickingInfo();
  13604. };
  13605. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13606. var _this = this;
  13607. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13608. /// <param name="x">X position on screen</param>
  13609. /// <param name="y">Y position on screen</param>
  13610. /// <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>
  13611. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13612. /// <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>
  13613. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13614. };
  13615. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13616. var _this = this;
  13617. return this._internalPick(function (world) {
  13618. if (!_this._pickWithRayInverseMatrix) {
  13619. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13620. }
  13621. world.invertToRef(_this._pickWithRayInverseMatrix);
  13622. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13623. }, predicate, fastCheck);
  13624. };
  13625. Scene.prototype.setPointerOverMesh = function (mesh) {
  13626. if (this._pointerOverMesh === mesh) {
  13627. return;
  13628. }
  13629. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13630. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13631. }
  13632. this._pointerOverMesh = mesh;
  13633. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13634. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13635. }
  13636. };
  13637. Scene.prototype.getPointerOverMesh = function () {
  13638. return this._pointerOverMesh;
  13639. };
  13640. // Physics
  13641. Scene.prototype.getPhysicsEngine = function () {
  13642. return this._physicsEngine;
  13643. };
  13644. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13645. if (this._physicsEngine) {
  13646. return true;
  13647. }
  13648. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13649. if (!this._physicsEngine.isSupported()) {
  13650. this._physicsEngine = null;
  13651. return false;
  13652. }
  13653. this._physicsEngine._initialize(gravity);
  13654. return true;
  13655. };
  13656. Scene.prototype.disablePhysicsEngine = function () {
  13657. if (!this._physicsEngine) {
  13658. return;
  13659. }
  13660. this._physicsEngine.dispose();
  13661. this._physicsEngine = undefined;
  13662. };
  13663. Scene.prototype.isPhysicsEnabled = function () {
  13664. return this._physicsEngine !== undefined;
  13665. };
  13666. Scene.prototype.setGravity = function (gravity) {
  13667. if (!this._physicsEngine) {
  13668. return;
  13669. }
  13670. this._physicsEngine._setGravity(gravity);
  13671. };
  13672. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13673. if (parts.parts) {
  13674. options = parts;
  13675. parts = parts.parts;
  13676. }
  13677. if (!this._physicsEngine) {
  13678. return null;
  13679. }
  13680. for (var index = 0; index < parts.length; index++) {
  13681. var mesh = parts[index].mesh;
  13682. mesh._physicImpostor = parts[index].impostor;
  13683. mesh._physicsMass = options.mass / parts.length;
  13684. mesh._physicsFriction = options.friction;
  13685. mesh._physicRestitution = options.restitution;
  13686. }
  13687. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13688. };
  13689. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13690. for (var index = 0; index < compound.parts.length; index++) {
  13691. var mesh = compound.parts[index].mesh;
  13692. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13693. this._physicsEngine._unregisterMesh(mesh);
  13694. }
  13695. };
  13696. // Misc.
  13697. Scene.prototype.createDefaultCameraOrLight = function () {
  13698. // Light
  13699. if (this.lights.length === 0) {
  13700. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13701. }
  13702. // Camera
  13703. if (!this.activeCamera) {
  13704. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13705. // Compute position
  13706. var worldExtends = this.getWorldExtends();
  13707. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13708. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13709. camera.setTarget(worldCenter);
  13710. this.activeCamera = camera;
  13711. }
  13712. };
  13713. // Tags
  13714. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13715. if (tagsQuery === undefined) {
  13716. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13717. return list;
  13718. }
  13719. var listByTags = [];
  13720. forEach = forEach || (function (item) { return; });
  13721. for (var i in list) {
  13722. var item = list[i];
  13723. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13724. listByTags.push(item);
  13725. forEach(item);
  13726. }
  13727. }
  13728. return listByTags;
  13729. };
  13730. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13731. return this._getByTags(this.meshes, tagsQuery, forEach);
  13732. };
  13733. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13734. return this._getByTags(this.cameras, tagsQuery, forEach);
  13735. };
  13736. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13737. return this._getByTags(this.lights, tagsQuery, forEach);
  13738. };
  13739. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13740. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13741. };
  13742. // Statics
  13743. Scene._FOGMODE_NONE = 0;
  13744. Scene._FOGMODE_EXP = 1;
  13745. Scene._FOGMODE_EXP2 = 2;
  13746. Scene._FOGMODE_LINEAR = 3;
  13747. Scene.MinDeltaTime = 1.0;
  13748. Scene.MaxDeltaTime = 1000.0;
  13749. return Scene;
  13750. })();
  13751. BABYLON.Scene = Scene;
  13752. })(BABYLON || (BABYLON = {}));
  13753. //# sourceMappingURL=babylon.scene.js.map
  13754. var BABYLON;
  13755. (function (BABYLON) {
  13756. var VertexBuffer = (function () {
  13757. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13758. if (engine instanceof BABYLON.Mesh) {
  13759. this._engine = engine.getScene().getEngine();
  13760. }
  13761. else {
  13762. this._engine = engine;
  13763. }
  13764. this._updatable = updatable;
  13765. this._data = data;
  13766. if (!postponeInternalCreation) {
  13767. this.create();
  13768. }
  13769. this._kind = kind;
  13770. if (stride) {
  13771. this._strideSize = stride;
  13772. return;
  13773. }
  13774. // Deduce stride from kind
  13775. switch (kind) {
  13776. case VertexBuffer.PositionKind:
  13777. this._strideSize = 3;
  13778. break;
  13779. case VertexBuffer.NormalKind:
  13780. this._strideSize = 3;
  13781. break;
  13782. case VertexBuffer.UVKind:
  13783. this._strideSize = 2;
  13784. break;
  13785. case VertexBuffer.UV2Kind:
  13786. this._strideSize = 2;
  13787. break;
  13788. case VertexBuffer.ColorKind:
  13789. this._strideSize = 4;
  13790. break;
  13791. case VertexBuffer.MatricesIndicesKind:
  13792. this._strideSize = 4;
  13793. break;
  13794. case VertexBuffer.MatricesWeightsKind:
  13795. this._strideSize = 4;
  13796. break;
  13797. }
  13798. }
  13799. // Properties
  13800. VertexBuffer.prototype.isUpdatable = function () {
  13801. return this._updatable;
  13802. };
  13803. VertexBuffer.prototype.getData = function () {
  13804. return this._data;
  13805. };
  13806. VertexBuffer.prototype.getBuffer = function () {
  13807. return this._buffer;
  13808. };
  13809. VertexBuffer.prototype.getStrideSize = function () {
  13810. return this._strideSize;
  13811. };
  13812. // Methods
  13813. VertexBuffer.prototype.create = function (data) {
  13814. if (!data && this._buffer) {
  13815. return; // nothing to do
  13816. }
  13817. data = data || this._data;
  13818. if (!this._buffer) {
  13819. if (this._updatable) {
  13820. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13821. }
  13822. else {
  13823. this._buffer = this._engine.createVertexBuffer(data);
  13824. }
  13825. }
  13826. if (this._updatable) {
  13827. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13828. this._data = data;
  13829. }
  13830. };
  13831. VertexBuffer.prototype.update = function (data) {
  13832. this.create(data);
  13833. };
  13834. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13835. if (!this._buffer) {
  13836. return;
  13837. }
  13838. if (this._updatable) {
  13839. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13840. this._data = null;
  13841. }
  13842. };
  13843. VertexBuffer.prototype.dispose = function () {
  13844. if (!this._buffer) {
  13845. return;
  13846. }
  13847. if (this._engine._releaseBuffer(this._buffer)) {
  13848. this._buffer = null;
  13849. }
  13850. };
  13851. Object.defineProperty(VertexBuffer, "PositionKind", {
  13852. get: function () {
  13853. return VertexBuffer._PositionKind;
  13854. },
  13855. enumerable: true,
  13856. configurable: true
  13857. });
  13858. Object.defineProperty(VertexBuffer, "NormalKind", {
  13859. get: function () {
  13860. return VertexBuffer._NormalKind;
  13861. },
  13862. enumerable: true,
  13863. configurable: true
  13864. });
  13865. Object.defineProperty(VertexBuffer, "UVKind", {
  13866. get: function () {
  13867. return VertexBuffer._UVKind;
  13868. },
  13869. enumerable: true,
  13870. configurable: true
  13871. });
  13872. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13873. get: function () {
  13874. return VertexBuffer._UV2Kind;
  13875. },
  13876. enumerable: true,
  13877. configurable: true
  13878. });
  13879. Object.defineProperty(VertexBuffer, "ColorKind", {
  13880. get: function () {
  13881. return VertexBuffer._ColorKind;
  13882. },
  13883. enumerable: true,
  13884. configurable: true
  13885. });
  13886. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13887. get: function () {
  13888. return VertexBuffer._MatricesIndicesKind;
  13889. },
  13890. enumerable: true,
  13891. configurable: true
  13892. });
  13893. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13894. get: function () {
  13895. return VertexBuffer._MatricesWeightsKind;
  13896. },
  13897. enumerable: true,
  13898. configurable: true
  13899. });
  13900. // Enums
  13901. VertexBuffer._PositionKind = "position";
  13902. VertexBuffer._NormalKind = "normal";
  13903. VertexBuffer._UVKind = "uv";
  13904. VertexBuffer._UV2Kind = "uv2";
  13905. VertexBuffer._ColorKind = "color";
  13906. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13907. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13908. return VertexBuffer;
  13909. })();
  13910. BABYLON.VertexBuffer = VertexBuffer;
  13911. })(BABYLON || (BABYLON = {}));
  13912. //# sourceMappingURL=babylon.vertexBuffer.js.map
  13913. var __extends = this.__extends || function (d, b) {
  13914. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13915. function __() { this.constructor = d; }
  13916. __.prototype = b.prototype;
  13917. d.prototype = new __();
  13918. };
  13919. var BABYLON;
  13920. (function (BABYLON) {
  13921. /**
  13922. * Creates an instance based on a source mesh.
  13923. */
  13924. var InstancedMesh = (function (_super) {
  13925. __extends(InstancedMesh, _super);
  13926. function InstancedMesh(name, source) {
  13927. _super.call(this, name, source.getScene());
  13928. source.instances.push(this);
  13929. this._sourceMesh = source;
  13930. this.position.copyFrom(source.position);
  13931. this.rotation.copyFrom(source.rotation);
  13932. this.scaling.copyFrom(source.scaling);
  13933. if (source.rotationQuaternion) {
  13934. this.rotationQuaternion = source.rotationQuaternion.clone();
  13935. }
  13936. this.infiniteDistance = source.infiniteDistance;
  13937. this.setPivotMatrix(source.getPivotMatrix());
  13938. this.refreshBoundingInfo();
  13939. this._syncSubMeshes();
  13940. }
  13941. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13942. // Methods
  13943. get: function () {
  13944. return this._sourceMesh.receiveShadows;
  13945. },
  13946. enumerable: true,
  13947. configurable: true
  13948. });
  13949. Object.defineProperty(InstancedMesh.prototype, "material", {
  13950. get: function () {
  13951. return this._sourceMesh.material;
  13952. },
  13953. enumerable: true,
  13954. configurable: true
  13955. });
  13956. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13957. get: function () {
  13958. return this._sourceMesh.visibility;
  13959. },
  13960. enumerable: true,
  13961. configurable: true
  13962. });
  13963. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13964. get: function () {
  13965. return this._sourceMesh.skeleton;
  13966. },
  13967. enumerable: true,
  13968. configurable: true
  13969. });
  13970. InstancedMesh.prototype.getTotalVertices = function () {
  13971. return this._sourceMesh.getTotalVertices();
  13972. };
  13973. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13974. get: function () {
  13975. return this._sourceMesh;
  13976. },
  13977. enumerable: true,
  13978. configurable: true
  13979. });
  13980. InstancedMesh.prototype.getVerticesData = function (kind) {
  13981. return this._sourceMesh.getVerticesData(kind);
  13982. };
  13983. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13984. return this._sourceMesh.isVerticesDataPresent(kind);
  13985. };
  13986. InstancedMesh.prototype.getIndices = function () {
  13987. return this._sourceMesh.getIndices();
  13988. };
  13989. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13990. get: function () {
  13991. return this._sourceMesh._positions;
  13992. },
  13993. enumerable: true,
  13994. configurable: true
  13995. });
  13996. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13997. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13998. if (data) {
  13999. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14000. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14001. }
  14002. this._updateBoundingInfo();
  14003. };
  14004. InstancedMesh.prototype._preActivate = function () {
  14005. if (this._currentLOD) {
  14006. this._currentLOD._preActivate();
  14007. }
  14008. };
  14009. InstancedMesh.prototype._activate = function (renderId) {
  14010. if (this._currentLOD) {
  14011. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14012. }
  14013. };
  14014. InstancedMesh.prototype.getLOD = function (camera) {
  14015. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14016. if (this._currentLOD === this.sourceMesh) {
  14017. return this;
  14018. }
  14019. return this._currentLOD;
  14020. };
  14021. InstancedMesh.prototype._syncSubMeshes = function () {
  14022. this.releaseSubMeshes();
  14023. if (this._sourceMesh.subMeshes) {
  14024. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14025. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14026. }
  14027. }
  14028. };
  14029. InstancedMesh.prototype._generatePointsArray = function () {
  14030. return this._sourceMesh._generatePointsArray();
  14031. };
  14032. // Clone
  14033. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14034. var result = this._sourceMesh.createInstance(name);
  14035. // Deep copy
  14036. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14037. // Bounding info
  14038. this.refreshBoundingInfo();
  14039. // Parent
  14040. if (newParent) {
  14041. result.parent = newParent;
  14042. }
  14043. if (!doNotCloneChildren) {
  14044. // Children
  14045. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14046. var mesh = this.getScene().meshes[index];
  14047. if (mesh.parent === this) {
  14048. mesh.clone(mesh.name, result);
  14049. }
  14050. }
  14051. }
  14052. result.computeWorldMatrix(true);
  14053. return result;
  14054. };
  14055. // Dispoe
  14056. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14057. // Remove from mesh
  14058. var index = this._sourceMesh.instances.indexOf(this);
  14059. this._sourceMesh.instances.splice(index, 1);
  14060. _super.prototype.dispose.call(this, doNotRecurse);
  14061. };
  14062. return InstancedMesh;
  14063. })(BABYLON.AbstractMesh);
  14064. BABYLON.InstancedMesh = InstancedMesh;
  14065. })(BABYLON || (BABYLON = {}));
  14066. //# sourceMappingURL=babylon.instancedMesh.js.map
  14067. var __extends = this.__extends || function (d, b) {
  14068. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14069. function __() { this.constructor = d; }
  14070. __.prototype = b.prototype;
  14071. d.prototype = new __();
  14072. };
  14073. var BABYLON;
  14074. (function (BABYLON) {
  14075. var _InstancesBatch = (function () {
  14076. function _InstancesBatch() {
  14077. this.mustReturn = false;
  14078. this.visibleInstances = new Array();
  14079. this.renderSelf = new Array();
  14080. }
  14081. return _InstancesBatch;
  14082. })();
  14083. BABYLON._InstancesBatch = _InstancesBatch;
  14084. var Mesh = (function (_super) {
  14085. __extends(Mesh, _super);
  14086. /**
  14087. * @constructor
  14088. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14089. * @param {Scene} scene - The scene to add this mesh to.
  14090. * @param {Node} parent - The parent of this mesh, if it has one
  14091. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14092. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14093. * When false, achieved by calling a clone(), also passing False.
  14094. * This will make creation of children, recursive.
  14095. */
  14096. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14097. if (parent === void 0) { parent = null; }
  14098. _super.call(this, name, scene);
  14099. // Members
  14100. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14101. this.instances = new Array();
  14102. this._LODLevels = new Array();
  14103. this._onBeforeRenderCallbacks = new Array();
  14104. this._onAfterRenderCallbacks = new Array();
  14105. this._visibleInstances = {};
  14106. this._renderIdForInstances = new Array();
  14107. this._batchCache = new _InstancesBatch();
  14108. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14109. this._sideOrientation = Mesh._DEFAULTSIDE;
  14110. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14111. if (source) {
  14112. // Geometry
  14113. if (source._geometry) {
  14114. source._geometry.applyToMesh(this);
  14115. }
  14116. // Deep copy
  14117. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14118. // Material
  14119. this.material = source.material;
  14120. if (!doNotCloneChildren) {
  14121. // Children
  14122. for (var index = 0; index < scene.meshes.length; index++) {
  14123. var mesh = scene.meshes[index];
  14124. if (mesh.parent === source) {
  14125. // doNotCloneChildren is always going to be False
  14126. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14127. }
  14128. }
  14129. }
  14130. // Particles
  14131. for (index = 0; index < scene.particleSystems.length; index++) {
  14132. var system = scene.particleSystems[index];
  14133. if (system.emitter === source) {
  14134. system.clone(system.name, this);
  14135. }
  14136. }
  14137. this.computeWorldMatrix(true);
  14138. }
  14139. // Parent
  14140. if (parent !== null) {
  14141. this.parent = parent;
  14142. }
  14143. }
  14144. Object.defineProperty(Mesh, "FRONTSIDE", {
  14145. get: function () {
  14146. return Mesh._FRONTSIDE;
  14147. },
  14148. enumerable: true,
  14149. configurable: true
  14150. });
  14151. Object.defineProperty(Mesh, "BACKSIDE", {
  14152. get: function () {
  14153. return Mesh._BACKSIDE;
  14154. },
  14155. enumerable: true,
  14156. configurable: true
  14157. });
  14158. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14159. get: function () {
  14160. return Mesh._DOUBLESIDE;
  14161. },
  14162. enumerable: true,
  14163. configurable: true
  14164. });
  14165. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14166. get: function () {
  14167. return Mesh._DEFAULTSIDE;
  14168. },
  14169. enumerable: true,
  14170. configurable: true
  14171. });
  14172. Object.defineProperty(Mesh, "NO_CAP", {
  14173. get: function () {
  14174. return Mesh._NO_CAP;
  14175. },
  14176. enumerable: true,
  14177. configurable: true
  14178. });
  14179. Object.defineProperty(Mesh, "CAP_START", {
  14180. get: function () {
  14181. return Mesh._CAP_START;
  14182. },
  14183. enumerable: true,
  14184. configurable: true
  14185. });
  14186. Object.defineProperty(Mesh, "CAP_END", {
  14187. get: function () {
  14188. return Mesh._CAP_END;
  14189. },
  14190. enumerable: true,
  14191. configurable: true
  14192. });
  14193. Object.defineProperty(Mesh, "CAP_ALL", {
  14194. get: function () {
  14195. return Mesh._CAP_ALL;
  14196. },
  14197. enumerable: true,
  14198. configurable: true
  14199. });
  14200. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14201. // Methods
  14202. get: function () {
  14203. return this._LODLevels.length > 0;
  14204. },
  14205. enumerable: true,
  14206. configurable: true
  14207. });
  14208. Mesh.prototype._sortLODLevels = function () {
  14209. this._LODLevels.sort(function (a, b) {
  14210. if (a.distance < b.distance) {
  14211. return 1;
  14212. }
  14213. if (a.distance > b.distance) {
  14214. return -1;
  14215. }
  14216. return 0;
  14217. });
  14218. };
  14219. /**
  14220. * Add a mesh as LOD level triggered at the given distance.
  14221. * @param {number} distance - the distance from the center of the object to show this level
  14222. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14223. * @return {BABYLON.Mesh} this mesh (for chaining)
  14224. */
  14225. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14226. if (mesh && mesh._masterMesh) {
  14227. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14228. return this;
  14229. }
  14230. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14231. this._LODLevels.push(level);
  14232. if (mesh) {
  14233. mesh._masterMesh = this;
  14234. }
  14235. this._sortLODLevels();
  14236. return this;
  14237. };
  14238. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14239. for (var index = 0; index < this._LODLevels.length; index++) {
  14240. var level = this._LODLevels[index];
  14241. if (level.distance === distance) {
  14242. return level.mesh;
  14243. }
  14244. }
  14245. return null;
  14246. };
  14247. /**
  14248. * Remove a mesh from the LOD array
  14249. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14250. * @return {BABYLON.Mesh} this mesh (for chaining)
  14251. */
  14252. Mesh.prototype.removeLODLevel = function (mesh) {
  14253. for (var index = 0; index < this._LODLevels.length; index++) {
  14254. if (this._LODLevels[index].mesh === mesh) {
  14255. this._LODLevels.splice(index, 1);
  14256. if (mesh) {
  14257. mesh._masterMesh = null;
  14258. }
  14259. }
  14260. }
  14261. this._sortLODLevels();
  14262. return this;
  14263. };
  14264. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14265. if (!this._LODLevels || this._LODLevels.length === 0) {
  14266. return this;
  14267. }
  14268. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14269. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14270. if (this.onLODLevelSelection) {
  14271. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14272. }
  14273. return this;
  14274. }
  14275. for (var index = 0; index < this._LODLevels.length; index++) {
  14276. var level = this._LODLevels[index];
  14277. if (level.distance < distanceToCamera) {
  14278. if (level.mesh) {
  14279. level.mesh._preActivate();
  14280. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14281. }
  14282. if (this.onLODLevelSelection) {
  14283. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14284. }
  14285. return level.mesh;
  14286. }
  14287. }
  14288. if (this.onLODLevelSelection) {
  14289. this.onLODLevelSelection(distanceToCamera, this, this);
  14290. }
  14291. return this;
  14292. };
  14293. Object.defineProperty(Mesh.prototype, "geometry", {
  14294. get: function () {
  14295. return this._geometry;
  14296. },
  14297. enumerable: true,
  14298. configurable: true
  14299. });
  14300. Mesh.prototype.getTotalVertices = function () {
  14301. if (!this._geometry) {
  14302. return 0;
  14303. }
  14304. return this._geometry.getTotalVertices();
  14305. };
  14306. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14307. if (!this._geometry) {
  14308. return null;
  14309. }
  14310. return this._geometry.getVerticesData(kind, copyWhenShared);
  14311. };
  14312. Mesh.prototype.getVertexBuffer = function (kind) {
  14313. if (!this._geometry) {
  14314. return undefined;
  14315. }
  14316. return this._geometry.getVertexBuffer(kind);
  14317. };
  14318. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14319. if (!this._geometry) {
  14320. if (this._delayInfo) {
  14321. return this._delayInfo.indexOf(kind) !== -1;
  14322. }
  14323. return false;
  14324. }
  14325. return this._geometry.isVerticesDataPresent(kind);
  14326. };
  14327. Mesh.prototype.getVerticesDataKinds = function () {
  14328. if (!this._geometry) {
  14329. var result = [];
  14330. if (this._delayInfo) {
  14331. for (var kind in this._delayInfo) {
  14332. result.push(kind);
  14333. }
  14334. }
  14335. return result;
  14336. }
  14337. return this._geometry.getVerticesDataKinds();
  14338. };
  14339. Mesh.prototype.getTotalIndices = function () {
  14340. if (!this._geometry) {
  14341. return 0;
  14342. }
  14343. return this._geometry.getTotalIndices();
  14344. };
  14345. Mesh.prototype.getIndices = function (copyWhenShared) {
  14346. if (!this._geometry) {
  14347. return [];
  14348. }
  14349. return this._geometry.getIndices(copyWhenShared);
  14350. };
  14351. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14352. get: function () {
  14353. return this._masterMesh !== null && this._masterMesh !== undefined;
  14354. },
  14355. enumerable: true,
  14356. configurable: true
  14357. });
  14358. Mesh.prototype.isReady = function () {
  14359. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14360. return false;
  14361. }
  14362. return _super.prototype.isReady.call(this);
  14363. };
  14364. Mesh.prototype.isDisposed = function () {
  14365. return this._isDisposed;
  14366. };
  14367. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14368. get: function () {
  14369. return this._sideOrientation;
  14370. },
  14371. set: function (sideO) {
  14372. this._sideOrientation = sideO;
  14373. },
  14374. enumerable: true,
  14375. configurable: true
  14376. });
  14377. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14378. get: function () {
  14379. return this._areNormalsFrozen;
  14380. },
  14381. enumerable: true,
  14382. configurable: true
  14383. });
  14384. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14385. Mesh.prototype.freezeNormals = function () {
  14386. this._areNormalsFrozen = true;
  14387. };
  14388. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14389. Mesh.prototype.unfreezeNormals = function () {
  14390. this._areNormalsFrozen = false;
  14391. };
  14392. // Methods
  14393. Mesh.prototype._preActivate = function () {
  14394. var sceneRenderId = this.getScene().getRenderId();
  14395. if (this._preActivateId === sceneRenderId) {
  14396. return;
  14397. }
  14398. this._preActivateId = sceneRenderId;
  14399. this._visibleInstances = null;
  14400. };
  14401. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14402. if (!this._visibleInstances) {
  14403. this._visibleInstances = {};
  14404. this._visibleInstances.defaultRenderId = renderId;
  14405. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14406. }
  14407. if (!this._visibleInstances[renderId]) {
  14408. this._visibleInstances[renderId] = new Array();
  14409. }
  14410. this._visibleInstances[renderId].push(instance);
  14411. };
  14412. Mesh.prototype.refreshBoundingInfo = function () {
  14413. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14414. if (data) {
  14415. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14416. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14417. }
  14418. if (this.subMeshes) {
  14419. for (var index = 0; index < this.subMeshes.length; index++) {
  14420. this.subMeshes[index].refreshBoundingInfo();
  14421. }
  14422. }
  14423. this._updateBoundingInfo();
  14424. };
  14425. Mesh.prototype._createGlobalSubMesh = function () {
  14426. var totalVertices = this.getTotalVertices();
  14427. if (!totalVertices || !this.getIndices()) {
  14428. return null;
  14429. }
  14430. this.releaseSubMeshes();
  14431. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14432. };
  14433. Mesh.prototype.subdivide = function (count) {
  14434. if (count < 1) {
  14435. return;
  14436. }
  14437. var totalIndices = this.getTotalIndices();
  14438. var subdivisionSize = (totalIndices / count) | 0;
  14439. var offset = 0;
  14440. // Ensure that subdivisionSize is a multiple of 3
  14441. while (subdivisionSize % 3 !== 0) {
  14442. subdivisionSize++;
  14443. }
  14444. this.releaseSubMeshes();
  14445. for (var index = 0; index < count; index++) {
  14446. if (offset >= totalIndices) {
  14447. break;
  14448. }
  14449. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14450. offset += subdivisionSize;
  14451. }
  14452. this.synchronizeInstances();
  14453. };
  14454. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14455. if (kind instanceof Array) {
  14456. var temp = data;
  14457. data = kind;
  14458. kind = temp;
  14459. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14460. }
  14461. if (!this._geometry) {
  14462. var vertexData = new BABYLON.VertexData();
  14463. vertexData.set(data, kind);
  14464. var scene = this.getScene();
  14465. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14466. }
  14467. else {
  14468. this._geometry.setVerticesData(kind, data, updatable, stride);
  14469. }
  14470. };
  14471. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14472. if (!this._geometry) {
  14473. return;
  14474. }
  14475. if (!makeItUnique) {
  14476. this._geometry.updateVerticesData(kind, data, updateExtends);
  14477. }
  14478. else {
  14479. this.makeGeometryUnique();
  14480. this.updateVerticesData(kind, data, updateExtends, false);
  14481. }
  14482. };
  14483. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14484. if (!this._geometry) {
  14485. return;
  14486. }
  14487. if (!makeItUnique) {
  14488. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14489. }
  14490. else {
  14491. this.makeGeometryUnique();
  14492. this.updateVerticesDataDirectly(kind, data, offset, false);
  14493. }
  14494. };
  14495. // Mesh positions update function :
  14496. // updates the mesh positions according to the positionFunction returned values.
  14497. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14498. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14499. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14500. if (computeNormals === void 0) { computeNormals = true; }
  14501. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14502. positionFunction(positions);
  14503. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14504. if (computeNormals) {
  14505. var indices = this.getIndices();
  14506. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14507. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14508. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14509. }
  14510. };
  14511. Mesh.prototype.makeGeometryUnique = function () {
  14512. if (!this._geometry) {
  14513. return;
  14514. }
  14515. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14516. geometry.applyToMesh(this);
  14517. };
  14518. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14519. if (!this._geometry) {
  14520. var vertexData = new BABYLON.VertexData();
  14521. vertexData.indices = indices;
  14522. var scene = this.getScene();
  14523. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14524. }
  14525. else {
  14526. this._geometry.setIndices(indices, totalVertices);
  14527. }
  14528. };
  14529. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14530. var engine = this.getScene().getEngine();
  14531. // Wireframe
  14532. var indexToBind;
  14533. switch (fillMode) {
  14534. case BABYLON.Material.PointFillMode:
  14535. indexToBind = null;
  14536. break;
  14537. case BABYLON.Material.WireFrameFillMode:
  14538. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14539. break;
  14540. default:
  14541. case BABYLON.Material.TriangleFillMode:
  14542. indexToBind = this._geometry.getIndexBuffer();
  14543. break;
  14544. }
  14545. // VBOs
  14546. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14547. };
  14548. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14549. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14550. return;
  14551. }
  14552. var engine = this.getScene().getEngine();
  14553. // Draw order
  14554. switch (fillMode) {
  14555. case BABYLON.Material.PointFillMode:
  14556. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14557. break;
  14558. case BABYLON.Material.WireFrameFillMode:
  14559. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14560. break;
  14561. default:
  14562. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14563. }
  14564. };
  14565. Mesh.prototype.registerBeforeRender = function (func) {
  14566. this._onBeforeRenderCallbacks.push(func);
  14567. };
  14568. Mesh.prototype.unregisterBeforeRender = function (func) {
  14569. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14570. if (index > -1) {
  14571. this._onBeforeRenderCallbacks.splice(index, 1);
  14572. }
  14573. };
  14574. Mesh.prototype.registerAfterRender = function (func) {
  14575. this._onAfterRenderCallbacks.push(func);
  14576. };
  14577. Mesh.prototype.unregisterAfterRender = function (func) {
  14578. var index = this._onAfterRenderCallbacks.indexOf(func);
  14579. if (index > -1) {
  14580. this._onAfterRenderCallbacks.splice(index, 1);
  14581. }
  14582. };
  14583. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14584. var scene = this.getScene();
  14585. this._batchCache.mustReturn = false;
  14586. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14587. this._batchCache.visibleInstances[subMeshId] = null;
  14588. if (this._visibleInstances) {
  14589. var currentRenderId = scene.getRenderId();
  14590. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14591. var selfRenderId = this._renderId;
  14592. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14593. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14594. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14595. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14596. }
  14597. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14598. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14599. this._batchCache.mustReturn = true;
  14600. return this._batchCache;
  14601. }
  14602. if (currentRenderId !== selfRenderId) {
  14603. this._batchCache.renderSelf[subMeshId] = false;
  14604. }
  14605. }
  14606. this._renderIdForInstances[subMeshId] = currentRenderId;
  14607. }
  14608. return this._batchCache;
  14609. };
  14610. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14611. var visibleInstances = batch.visibleInstances[subMesh._id];
  14612. var matricesCount = visibleInstances.length + 1;
  14613. var bufferSize = matricesCount * 16 * 4;
  14614. while (this._instancesBufferSize < bufferSize) {
  14615. this._instancesBufferSize *= 2;
  14616. }
  14617. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14618. if (this._worldMatricesInstancesBuffer) {
  14619. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14620. }
  14621. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14622. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14623. }
  14624. var offset = 0;
  14625. var instancesCount = 0;
  14626. var world = this.getWorldMatrix();
  14627. if (batch.renderSelf[subMesh._id]) {
  14628. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14629. offset += 16;
  14630. instancesCount++;
  14631. }
  14632. if (visibleInstances) {
  14633. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14634. var instance = visibleInstances[instanceIndex];
  14635. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14636. offset += 16;
  14637. instancesCount++;
  14638. }
  14639. }
  14640. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14641. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14642. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14643. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14644. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14645. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14646. this._draw(subMesh, fillMode, instancesCount);
  14647. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14648. };
  14649. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14650. var scene = this.getScene();
  14651. var engine = scene.getEngine();
  14652. if (hardwareInstancedRendering) {
  14653. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14654. }
  14655. else {
  14656. if (batch.renderSelf[subMesh._id]) {
  14657. // Draw
  14658. if (onBeforeDraw) {
  14659. onBeforeDraw(false, this.getWorldMatrix());
  14660. }
  14661. this._draw(subMesh, fillMode);
  14662. }
  14663. if (batch.visibleInstances[subMesh._id]) {
  14664. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14665. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14666. // World
  14667. var world = instance.getWorldMatrix();
  14668. if (onBeforeDraw) {
  14669. onBeforeDraw(true, world);
  14670. }
  14671. // Draw
  14672. this._draw(subMesh, fillMode);
  14673. }
  14674. }
  14675. }
  14676. };
  14677. Mesh.prototype.render = function (subMesh) {
  14678. var scene = this.getScene();
  14679. // Managing instances
  14680. var batch = this._getInstancesRenderList(subMesh._id);
  14681. if (batch.mustReturn) {
  14682. return;
  14683. }
  14684. // Checking geometry state
  14685. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14686. return;
  14687. }
  14688. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14689. this._onBeforeRenderCallbacks[callbackIndex](this);
  14690. }
  14691. var engine = scene.getEngine();
  14692. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14693. // Material
  14694. var effectiveMaterial = subMesh.getMaterial();
  14695. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14696. return;
  14697. }
  14698. // Outline - step 1
  14699. var savedDepthWrite = engine.getDepthWrite();
  14700. if (this.renderOutline) {
  14701. engine.setDepthWrite(false);
  14702. scene.getOutlineRenderer().render(subMesh, batch);
  14703. engine.setDepthWrite(savedDepthWrite);
  14704. }
  14705. effectiveMaterial._preBind();
  14706. var effect = effectiveMaterial.getEffect();
  14707. // Bind
  14708. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14709. this._bind(subMesh, effect, fillMode);
  14710. var world = this.getWorldMatrix();
  14711. effectiveMaterial.bind(world, this);
  14712. // Draw
  14713. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14714. if (isInstance) {
  14715. effectiveMaterial.bindOnlyWorldMatrix(world);
  14716. }
  14717. });
  14718. // Unbind
  14719. effectiveMaterial.unbind();
  14720. // Outline - step 2
  14721. if (this.renderOutline && savedDepthWrite) {
  14722. engine.setDepthWrite(true);
  14723. engine.setColorWrite(false);
  14724. scene.getOutlineRenderer().render(subMesh, batch);
  14725. engine.setColorWrite(true);
  14726. }
  14727. // Overlay
  14728. if (this.renderOverlay) {
  14729. var currentMode = engine.getAlphaMode();
  14730. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14731. scene.getOutlineRenderer().render(subMesh, batch, true);
  14732. engine.setAlphaMode(currentMode);
  14733. }
  14734. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14735. this._onAfterRenderCallbacks[callbackIndex](this);
  14736. }
  14737. };
  14738. Mesh.prototype.getEmittedParticleSystems = function () {
  14739. var results = new Array();
  14740. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14741. var particleSystem = this.getScene().particleSystems[index];
  14742. if (particleSystem.emitter === this) {
  14743. results.push(particleSystem);
  14744. }
  14745. }
  14746. return results;
  14747. };
  14748. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14749. var results = new Array();
  14750. var descendants = this.getDescendants();
  14751. descendants.push(this);
  14752. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14753. var particleSystem = this.getScene().particleSystems[index];
  14754. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14755. results.push(particleSystem);
  14756. }
  14757. }
  14758. return results;
  14759. };
  14760. Mesh.prototype.getChildren = function () {
  14761. var results = [];
  14762. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14763. var mesh = this.getScene().meshes[index];
  14764. if (mesh.parent === this) {
  14765. results.push(mesh);
  14766. }
  14767. }
  14768. return results;
  14769. };
  14770. Mesh.prototype._checkDelayState = function () {
  14771. var _this = this;
  14772. var that = this;
  14773. var scene = this.getScene();
  14774. if (this._geometry) {
  14775. this._geometry.load(scene);
  14776. }
  14777. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14778. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14779. scene._addPendingData(that);
  14780. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14781. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14782. if (data instanceof ArrayBuffer) {
  14783. _this._delayLoadingFunction(data, _this);
  14784. }
  14785. else {
  14786. _this._delayLoadingFunction(JSON.parse(data), _this);
  14787. }
  14788. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14789. scene._removePendingData(_this);
  14790. }, function () { }, scene.database, getBinaryData);
  14791. }
  14792. };
  14793. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14794. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14795. return false;
  14796. }
  14797. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14798. return false;
  14799. }
  14800. this._checkDelayState();
  14801. return true;
  14802. };
  14803. Mesh.prototype.setMaterialByID = function (id) {
  14804. var materials = this.getScene().materials;
  14805. for (var index = 0; index < materials.length; index++) {
  14806. if (materials[index].id === id) {
  14807. this.material = materials[index];
  14808. return;
  14809. }
  14810. }
  14811. // Multi
  14812. var multiMaterials = this.getScene().multiMaterials;
  14813. for (index = 0; index < multiMaterials.length; index++) {
  14814. if (multiMaterials[index].id === id) {
  14815. this.material = multiMaterials[index];
  14816. return;
  14817. }
  14818. }
  14819. };
  14820. Mesh.prototype.getAnimatables = function () {
  14821. var results = [];
  14822. if (this.material) {
  14823. results.push(this.material);
  14824. }
  14825. if (this.skeleton) {
  14826. results.push(this.skeleton);
  14827. }
  14828. return results;
  14829. };
  14830. // Geometry
  14831. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14832. // Position
  14833. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14834. return;
  14835. }
  14836. this._resetPointsArrayCache();
  14837. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14838. var temp = [];
  14839. for (var index = 0; index < data.length; index += 3) {
  14840. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14841. }
  14842. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14843. // Normals
  14844. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14845. return;
  14846. }
  14847. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14848. temp = [];
  14849. for (index = 0; index < data.length; index += 3) {
  14850. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14851. }
  14852. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14853. };
  14854. // Cache
  14855. Mesh.prototype._resetPointsArrayCache = function () {
  14856. this._positions = null;
  14857. };
  14858. Mesh.prototype._generatePointsArray = function () {
  14859. if (this._positions)
  14860. return true;
  14861. this._positions = [];
  14862. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14863. if (!data) {
  14864. return false;
  14865. }
  14866. for (var index = 0; index < data.length; index += 3) {
  14867. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14868. }
  14869. return true;
  14870. };
  14871. // Clone
  14872. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14873. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14874. };
  14875. // Dispose
  14876. Mesh.prototype.dispose = function (doNotRecurse) {
  14877. if (this._geometry) {
  14878. this._geometry.releaseForMesh(this, true);
  14879. }
  14880. // Instances
  14881. if (this._worldMatricesInstancesBuffer) {
  14882. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14883. this._worldMatricesInstancesBuffer = null;
  14884. }
  14885. while (this.instances.length) {
  14886. this.instances[0].dispose();
  14887. }
  14888. _super.prototype.dispose.call(this, doNotRecurse);
  14889. };
  14890. // Geometric tools
  14891. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14892. var _this = this;
  14893. var scene = this.getScene();
  14894. var onload = function (img) {
  14895. // Getting height map data
  14896. var canvas = document.createElement("canvas");
  14897. var context = canvas.getContext("2d");
  14898. var heightMapWidth = img.width;
  14899. var heightMapHeight = img.height;
  14900. canvas.width = heightMapWidth;
  14901. canvas.height = heightMapHeight;
  14902. context.drawImage(img, 0, 0);
  14903. // Create VertexData from map data
  14904. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14905. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14906. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14907. //execute success callback, if set
  14908. if (onSuccess) {
  14909. onSuccess(_this);
  14910. }
  14911. };
  14912. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14913. };
  14914. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14915. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14916. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14917. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14918. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14919. return;
  14920. }
  14921. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14922. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14923. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14924. var position = BABYLON.Vector3.Zero();
  14925. var normal = BABYLON.Vector3.Zero();
  14926. var uv = BABYLON.Vector2.Zero();
  14927. for (var index = 0; index < positions.length; index += 3) {
  14928. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14929. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14930. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14931. // Compute height
  14932. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14933. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14934. var pos = (u + v * heightMapWidth) * 4;
  14935. var r = buffer[pos] / 255.0;
  14936. var g = buffer[pos + 1] / 255.0;
  14937. var b = buffer[pos + 2] / 255.0;
  14938. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14939. normal.normalize();
  14940. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14941. position = position.add(normal);
  14942. position.toArray(positions, index);
  14943. }
  14944. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14945. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14946. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14947. };
  14948. Mesh.prototype.convertToFlatShadedMesh = function () {
  14949. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14950. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14951. var kinds = this.getVerticesDataKinds();
  14952. var vbs = [];
  14953. var data = [];
  14954. var newdata = [];
  14955. var updatableNormals = false;
  14956. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14957. var kind = kinds[kindIndex];
  14958. var vertexBuffer = this.getVertexBuffer(kind);
  14959. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14960. updatableNormals = vertexBuffer.isUpdatable();
  14961. kinds.splice(kindIndex, 1);
  14962. kindIndex--;
  14963. continue;
  14964. }
  14965. vbs[kind] = vertexBuffer;
  14966. data[kind] = vbs[kind].getData();
  14967. newdata[kind] = [];
  14968. }
  14969. // Save previous submeshes
  14970. var previousSubmeshes = this.subMeshes.slice(0);
  14971. var indices = this.getIndices();
  14972. var totalIndices = this.getTotalIndices();
  14973. // Generating unique vertices per face
  14974. for (var index = 0; index < totalIndices; index++) {
  14975. var vertexIndex = indices[index];
  14976. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14977. kind = kinds[kindIndex];
  14978. var stride = vbs[kind].getStrideSize();
  14979. for (var offset = 0; offset < stride; offset++) {
  14980. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14981. }
  14982. }
  14983. }
  14984. // Updating faces & normal
  14985. var normals = [];
  14986. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14987. for (index = 0; index < totalIndices; index += 3) {
  14988. indices[index] = index;
  14989. indices[index + 1] = index + 1;
  14990. indices[index + 2] = index + 2;
  14991. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14992. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14993. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14994. var p1p2 = p1.subtract(p2);
  14995. var p3p2 = p3.subtract(p2);
  14996. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14997. // Store same normals for every vertex
  14998. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14999. normals.push(normal.x);
  15000. normals.push(normal.y);
  15001. normals.push(normal.z);
  15002. }
  15003. }
  15004. this.setIndices(indices);
  15005. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15006. // Updating vertex buffers
  15007. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15008. kind = kinds[kindIndex];
  15009. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15010. }
  15011. // Updating submeshes
  15012. this.releaseSubMeshes();
  15013. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15014. var previousOne = previousSubmeshes[submeshIndex];
  15015. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15016. }
  15017. this.synchronizeInstances();
  15018. };
  15019. // Instances
  15020. Mesh.prototype.createInstance = function (name) {
  15021. return new BABYLON.InstancedMesh(name, this);
  15022. };
  15023. Mesh.prototype.synchronizeInstances = function () {
  15024. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15025. var instance = this.instances[instanceIndex];
  15026. instance._syncSubMeshes();
  15027. }
  15028. };
  15029. /**
  15030. * Simplify the mesh according to the given array of settings.
  15031. * Function will return immediately and will simplify async.
  15032. * @param settings a collection of simplification settings.
  15033. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15034. * @param type the type of simplification to run.
  15035. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15036. */
  15037. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15038. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15039. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15040. this.getScene().simplificationQueue.addTask({
  15041. settings: settings,
  15042. parallelProcessing: parallelProcessing,
  15043. mesh: this,
  15044. simplificationType: simplificationType,
  15045. successCallback: successCallback
  15046. });
  15047. };
  15048. /**
  15049. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15050. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15051. * This should be used together with the simplification to avoid disappearing triangles.
  15052. * @param successCallback an optional success callback to be called after the optimization finished.
  15053. */
  15054. Mesh.prototype.optimizeIndices = function (successCallback) {
  15055. var _this = this;
  15056. var indices = this.getIndices();
  15057. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15058. var vectorPositions = [];
  15059. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15060. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15061. }
  15062. var dupes = [];
  15063. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15064. var realPos = vectorPositions.length - 1 - iteration;
  15065. var testedPosition = vectorPositions[realPos];
  15066. for (var j = 0; j < realPos; ++j) {
  15067. var againstPosition = vectorPositions[j];
  15068. if (testedPosition.equals(againstPosition)) {
  15069. dupes[realPos] = j;
  15070. break;
  15071. }
  15072. }
  15073. }, function () {
  15074. for (var i = 0; i < indices.length; ++i) {
  15075. indices[i] = dupes[indices[i]] || indices[i];
  15076. }
  15077. //indices are now reordered
  15078. var originalSubMeshes = _this.subMeshes.slice(0);
  15079. _this.setIndices(indices);
  15080. _this.subMeshes = originalSubMeshes;
  15081. if (successCallback) {
  15082. successCallback(_this);
  15083. }
  15084. });
  15085. };
  15086. // Statics
  15087. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15088. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15089. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15090. if (ribbonInstance) {
  15091. // positionFunction : ribbon case
  15092. // only pathArray and sideOrientation parameters are taken into account for positions update
  15093. var positionFunction = function (positions) {
  15094. var minlg = pathArray[0].length;
  15095. var i = 0;
  15096. var ns = (ribbonInstance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  15097. for (var si = 1; si <= ns; si++) {
  15098. for (var p = 0; p < pathArray.length; p++) {
  15099. var path = pathArray[p];
  15100. var l = path.length;
  15101. minlg = (minlg < l) ? minlg : l;
  15102. var j = 0;
  15103. while (j < minlg) {
  15104. positions[i] = path[j].x;
  15105. positions[i + 1] = path[j].y;
  15106. positions[i + 2] = path[j].z;
  15107. j++;
  15108. i += 3;
  15109. }
  15110. }
  15111. }
  15112. };
  15113. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  15114. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  15115. return ribbonInstance;
  15116. }
  15117. else {
  15118. var ribbon = new Mesh(name, scene);
  15119. ribbon.sideOrientation = sideOrientation;
  15120. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15121. vertexData.applyToMesh(ribbon, updatable);
  15122. return ribbon;
  15123. }
  15124. };
  15125. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15126. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15127. var disc = new Mesh(name, scene);
  15128. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15129. vertexData.applyToMesh(disc, updatable);
  15130. return disc;
  15131. };
  15132. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15133. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15134. var box = new Mesh(name, scene);
  15135. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  15136. vertexData.applyToMesh(box, updatable);
  15137. return box;
  15138. };
  15139. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15140. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15141. var sphere = new Mesh(name, scene);
  15142. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  15143. vertexData.applyToMesh(sphere, updatable);
  15144. return sphere;
  15145. };
  15146. // Cylinder and cone (Code inspired by SharpDX.org)
  15147. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15148. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15149. // subdivisions is a new parameter, we need to support old signature
  15150. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15151. if (scene !== undefined) {
  15152. updatable = scene;
  15153. }
  15154. scene = subdivisions;
  15155. subdivisions = 1;
  15156. }
  15157. var cylinder = new Mesh(name, scene);
  15158. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  15159. vertexData.applyToMesh(cylinder, updatable);
  15160. return cylinder;
  15161. };
  15162. // Torus (Code from SharpDX.org)
  15163. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15164. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15165. var torus = new Mesh(name, scene);
  15166. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15167. vertexData.applyToMesh(torus, updatable);
  15168. return torus;
  15169. };
  15170. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15171. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15172. var torusKnot = new Mesh(name, scene);
  15173. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15174. vertexData.applyToMesh(torusKnot, updatable);
  15175. return torusKnot;
  15176. };
  15177. // Lines
  15178. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15179. if (linesInstance === void 0) { linesInstance = null; }
  15180. if (linesInstance) {
  15181. var positionsOfLines = function (points) {
  15182. var positionFunction = function (positions) {
  15183. var i = 0;
  15184. for (var p = 0; p < points.length; p++) {
  15185. positions[i] = points[p].x;
  15186. positions[i + 1] = points[p].y;
  15187. positions[i + 2] = points[p].z;
  15188. i += 3;
  15189. }
  15190. };
  15191. return positionFunction;
  15192. };
  15193. var positionFunction = positionsOfLines(points);
  15194. linesInstance.updateMeshPositions(positionFunction, false);
  15195. return linesInstance;
  15196. }
  15197. // lines creation
  15198. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15199. var vertexData = BABYLON.VertexData.CreateLines(points);
  15200. vertexData.applyToMesh(lines, updatable);
  15201. return lines;
  15202. };
  15203. // Dashed Lines
  15204. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15205. if (linesInstance === void 0) { linesInstance = null; }
  15206. if (linesInstance) {
  15207. var positionFunction = function (positions) {
  15208. var curvect = BABYLON.Vector3.Zero();
  15209. var nbSeg = positions.length / 6;
  15210. var lg = 0;
  15211. var nb = 0;
  15212. var shft = 0;
  15213. var dashshft = 0;
  15214. var curshft = 0;
  15215. var p = 0;
  15216. var i = 0;
  15217. var j = 0;
  15218. for (i = 0; i < points.length - 1; i++) {
  15219. points[i + 1].subtractToRef(points[i], curvect);
  15220. lg += curvect.length();
  15221. }
  15222. shft = lg / nbSeg;
  15223. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15224. for (i = 0; i < points.length - 1; i++) {
  15225. points[i + 1].subtractToRef(points[i], curvect);
  15226. curvect.normalize();
  15227. nb = Math.floor(curvect.length() / shft);
  15228. j = 0;
  15229. while (j < nb && p < positions.length) {
  15230. curshft = shft * j;
  15231. positions[p] = points[i].x + curshft * curvect.x;
  15232. positions[p + 1] = points[i].y + curshft * curvect.y;
  15233. positions[p + 2] = points[i].z + curshft * curvect.z;
  15234. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15235. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15236. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15237. p += 6;
  15238. j++;
  15239. }
  15240. }
  15241. while (p < positions.length) {
  15242. positions[p] = points[i].x;
  15243. positions[p + 1] = points[i].y;
  15244. positions[p + 2] = points[i].z;
  15245. p += 3;
  15246. }
  15247. };
  15248. linesInstance.updateMeshPositions(positionFunction, false);
  15249. return linesInstance;
  15250. }
  15251. // dashed lines creation
  15252. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15253. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15254. vertexData.applyToMesh(dashedLines, updatable);
  15255. dashedLines.dashSize = dashSize;
  15256. dashedLines.gapSize = gapSize;
  15257. return dashedLines;
  15258. };
  15259. // Extrusion
  15260. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15261. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15262. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15263. scale = scale || 1;
  15264. rotation = rotation || 0;
  15265. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15266. return extruded;
  15267. };
  15268. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15269. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15270. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15271. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15272. return extrudedCustom;
  15273. };
  15274. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15275. // extrusion geometry
  15276. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15277. var tangents = path3D.getTangents();
  15278. var normals = path3D.getNormals();
  15279. var binormals = path3D.getBinormals();
  15280. var distances = path3D.getDistances();
  15281. var angle = 0;
  15282. var returnScale = function (i, distance) { return scale; };
  15283. var returnRotation = function (i, distance) { return rotation; };
  15284. var rotate = custom ? rotateFunction : returnRotation;
  15285. var scl = custom ? scaleFunction : returnScale;
  15286. var index = 0;
  15287. for (var i = 0; i < curve.length; i++) {
  15288. var shapePath = new Array();
  15289. var angleStep = rotate(i, distances[i]);
  15290. var scaleRatio = scl(i, distances[i]);
  15291. for (var p = 0; p < shape.length; p++) {
  15292. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15293. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15294. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15295. shapePath.push(rotated);
  15296. }
  15297. shapePaths[index] = shapePath;
  15298. angle += angleStep;
  15299. index++;
  15300. }
  15301. // cap
  15302. var capPath = function (shapePath) {
  15303. var pointCap = Array();
  15304. var barycenter = BABYLON.Vector3.Zero();
  15305. var i;
  15306. for (i = 0; i < shapePath.length; i++) {
  15307. barycenter.addInPlace(shapePath[i]);
  15308. }
  15309. barycenter.scaleInPlace(1 / shapePath.length);
  15310. for (i = 0; i < shapePath.length; i++) {
  15311. pointCap.push(barycenter);
  15312. }
  15313. return pointCap;
  15314. };
  15315. switch (cap) {
  15316. case BABYLON.Mesh.NO_CAP:
  15317. break;
  15318. case BABYLON.Mesh.CAP_START:
  15319. shapePaths.unshift(capPath(shapePaths[0]));
  15320. break;
  15321. case BABYLON.Mesh.CAP_END:
  15322. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15323. break;
  15324. case BABYLON.Mesh.CAP_ALL:
  15325. shapePaths.unshift(capPath(shapePaths[0]));
  15326. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15327. break;
  15328. default:
  15329. break;
  15330. }
  15331. return shapePaths;
  15332. };
  15333. if (instance) {
  15334. var path3D = (instance.path3D).update(curve);
  15335. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15336. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15337. return instance;
  15338. }
  15339. // extruded shape creation
  15340. var path3D = new BABYLON.Path3D(curve);
  15341. var newShapePaths = new Array();
  15342. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15343. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15344. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15345. extrudedGeneric.pathArray = pathArray;
  15346. extrudedGeneric.path3D = path3D;
  15347. extrudedGeneric.cap = cap;
  15348. return extrudedGeneric;
  15349. };
  15350. // Plane & ground
  15351. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15352. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15353. var plane = new Mesh(name, scene);
  15354. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  15355. vertexData.applyToMesh(plane, updatable);
  15356. return plane;
  15357. };
  15358. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15359. var ground = new BABYLON.GroundMesh(name, scene);
  15360. ground._setReady(false);
  15361. ground._subdivisions = subdivisions;
  15362. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  15363. vertexData.applyToMesh(ground, updatable);
  15364. ground._setReady(true);
  15365. return ground;
  15366. };
  15367. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15368. var tiledGround = new Mesh(name, scene);
  15369. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15370. vertexData.applyToMesh(tiledGround, updatable);
  15371. return tiledGround;
  15372. };
  15373. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15374. var ground = new BABYLON.GroundMesh(name, scene);
  15375. ground._subdivisions = subdivisions;
  15376. ground._setReady(false);
  15377. var onload = function (img) {
  15378. // Getting height map data
  15379. var canvas = document.createElement("canvas");
  15380. var context = canvas.getContext("2d");
  15381. var heightMapWidth = img.width;
  15382. var heightMapHeight = img.height;
  15383. canvas.width = heightMapWidth;
  15384. canvas.height = heightMapHeight;
  15385. context.drawImage(img, 0, 0);
  15386. // Create VertexData from map data
  15387. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15388. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15389. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15390. vertexData.applyToMesh(ground, updatable);
  15391. ground._setReady(true);
  15392. //execute ready callback, if set
  15393. if (onReady) {
  15394. onReady(ground);
  15395. }
  15396. };
  15397. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15398. return ground;
  15399. };
  15400. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15401. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15402. if (tubeInstance === void 0) { tubeInstance = null; }
  15403. // tube geometry
  15404. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15405. var tangents = path3D.getTangents();
  15406. var normals = path3D.getNormals();
  15407. var distances = path3D.getDistances();
  15408. var pi2 = Math.PI * 2;
  15409. var step = pi2 / tessellation;
  15410. var returnRadius = function (i, distance) { return radius; };
  15411. var radiusFunctionFinal = radiusFunction || returnRadius;
  15412. var circlePath;
  15413. var rad;
  15414. var normal;
  15415. var rotated;
  15416. var rotationMatrix;
  15417. var index = 0;
  15418. for (var i = 0; i < path.length; i++) {
  15419. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15420. circlePath = Array(); // current circle array
  15421. normal = normals[i]; // current normal
  15422. for (var t = 0; t < tessellation; t++) {
  15423. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15424. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15425. circlePath.push(rotated);
  15426. }
  15427. circlePath.push(circlePath[0]);
  15428. circlePaths[index] = circlePath;
  15429. index++;
  15430. }
  15431. // cap
  15432. var capPath = function (nbPoints, pathIndex) {
  15433. var pointCap = Array();
  15434. for (var i = 0; i < nbPoints; i++) {
  15435. pointCap.push(path[pathIndex]);
  15436. }
  15437. return pointCap;
  15438. };
  15439. switch (cap) {
  15440. case BABYLON.Mesh.NO_CAP:
  15441. break;
  15442. case BABYLON.Mesh.CAP_START:
  15443. circlePaths.unshift(capPath(tessellation + 1, 0));
  15444. break;
  15445. case BABYLON.Mesh.CAP_END:
  15446. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15447. break;
  15448. case BABYLON.Mesh.CAP_ALL:
  15449. circlePaths.unshift(capPath(tessellation + 1, 0));
  15450. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15451. break;
  15452. default:
  15453. break;
  15454. }
  15455. return circlePaths;
  15456. };
  15457. if (tubeInstance) {
  15458. var path3D = (tubeInstance.path3D).update(path);
  15459. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  15460. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  15461. return tubeInstance;
  15462. }
  15463. // tube creation
  15464. var path3D = new BABYLON.Path3D(path);
  15465. var newPathArray = new Array();
  15466. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15467. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  15468. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  15469. tube.pathArray = pathArray;
  15470. tube.path3D = path3D;
  15471. tube.tessellation = tessellation;
  15472. tube.cap = cap;
  15473. return tube;
  15474. };
  15475. // Decals
  15476. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15477. if (angle === void 0) { angle = 0; }
  15478. var indices = sourceMesh.getIndices();
  15479. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15480. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15481. // Getting correct rotation
  15482. if (!normal) {
  15483. var target = new BABYLON.Vector3(0, 0, 1);
  15484. var camera = sourceMesh.getScene().activeCamera;
  15485. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15486. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15487. }
  15488. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15489. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15490. var pitch = Math.atan2(normal.y, len);
  15491. // Matrix
  15492. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15493. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15494. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15495. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15496. var vertexData = new BABYLON.VertexData();
  15497. vertexData.indices = [];
  15498. vertexData.positions = [];
  15499. vertexData.normals = [];
  15500. vertexData.uvs = [];
  15501. var currentVertexDataIndex = 0;
  15502. var extractDecalVector3 = function (indexId) {
  15503. var vertexId = indices[indexId];
  15504. var result = new BABYLON.PositionNormalVertex();
  15505. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15506. // Send vector to decal local world
  15507. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15508. // Get normal
  15509. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15510. return result;
  15511. };
  15512. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15513. var clip = function (vertices, axis) {
  15514. if (vertices.length === 0) {
  15515. return vertices;
  15516. }
  15517. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15518. var clipVertices = function (v0, v1) {
  15519. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15520. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15521. };
  15522. var result = new Array();
  15523. for (var index = 0; index < vertices.length; index += 3) {
  15524. var v1Out;
  15525. var v2Out;
  15526. var v3Out;
  15527. var total = 0;
  15528. var nV1, nV2, nV3, nV4;
  15529. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15530. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15531. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15532. v1Out = d1 > 0;
  15533. v2Out = d2 > 0;
  15534. v3Out = d3 > 0;
  15535. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15536. switch (total) {
  15537. case 0:
  15538. result.push(vertices[index]);
  15539. result.push(vertices[index + 1]);
  15540. result.push(vertices[index + 2]);
  15541. break;
  15542. case 1:
  15543. if (v1Out) {
  15544. nV1 = vertices[index + 1];
  15545. nV2 = vertices[index + 2];
  15546. nV3 = clipVertices(vertices[index], nV1);
  15547. nV4 = clipVertices(vertices[index], nV2);
  15548. }
  15549. if (v2Out) {
  15550. nV1 = vertices[index];
  15551. nV2 = vertices[index + 2];
  15552. nV3 = clipVertices(vertices[index + 1], nV1);
  15553. nV4 = clipVertices(vertices[index + 1], nV2);
  15554. result.push(nV3);
  15555. result.push(nV2.clone());
  15556. result.push(nV1.clone());
  15557. result.push(nV2.clone());
  15558. result.push(nV3.clone());
  15559. result.push(nV4);
  15560. break;
  15561. }
  15562. if (v3Out) {
  15563. nV1 = vertices[index];
  15564. nV2 = vertices[index + 1];
  15565. nV3 = clipVertices(vertices[index + 2], nV1);
  15566. nV4 = clipVertices(vertices[index + 2], nV2);
  15567. }
  15568. result.push(nV1.clone());
  15569. result.push(nV2.clone());
  15570. result.push(nV3);
  15571. result.push(nV4);
  15572. result.push(nV3.clone());
  15573. result.push(nV2.clone());
  15574. break;
  15575. case 2:
  15576. if (!v1Out) {
  15577. nV1 = vertices[index].clone();
  15578. nV2 = clipVertices(nV1, vertices[index + 1]);
  15579. nV3 = clipVertices(nV1, vertices[index + 2]);
  15580. result.push(nV1);
  15581. result.push(nV2);
  15582. result.push(nV3);
  15583. }
  15584. if (!v2Out) {
  15585. nV1 = vertices[index + 1].clone();
  15586. nV2 = clipVertices(nV1, vertices[index + 2]);
  15587. nV3 = clipVertices(nV1, vertices[index]);
  15588. result.push(nV1);
  15589. result.push(nV2);
  15590. result.push(nV3);
  15591. }
  15592. if (!v3Out) {
  15593. nV1 = vertices[index + 2].clone();
  15594. nV2 = clipVertices(nV1, vertices[index]);
  15595. nV3 = clipVertices(nV1, vertices[index + 1]);
  15596. result.push(nV1);
  15597. result.push(nV2);
  15598. result.push(nV3);
  15599. }
  15600. break;
  15601. case 3:
  15602. break;
  15603. }
  15604. }
  15605. return result;
  15606. };
  15607. for (var index = 0; index < indices.length; index += 3) {
  15608. var faceVertices = new Array();
  15609. faceVertices.push(extractDecalVector3(index));
  15610. faceVertices.push(extractDecalVector3(index + 1));
  15611. faceVertices.push(extractDecalVector3(index + 2));
  15612. // Clip
  15613. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15614. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  15615. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  15616. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  15617. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  15618. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  15619. if (faceVertices.length === 0) {
  15620. continue;
  15621. }
  15622. // Add UVs and get back to world
  15623. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  15624. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  15625. var vertex = faceVertices[vIndex];
  15626. vertexData.indices.push(currentVertexDataIndex);
  15627. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  15628. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  15629. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  15630. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  15631. currentVertexDataIndex++;
  15632. }
  15633. }
  15634. // Return mesh
  15635. var decal = new Mesh(name, sourceMesh.getScene());
  15636. vertexData.applyToMesh(decal);
  15637. decal.position = position.clone();
  15638. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  15639. return decal;
  15640. };
  15641. // Tools
  15642. Mesh.MinMax = function (meshes) {
  15643. var minVector = null;
  15644. var maxVector = null;
  15645. for (var i in meshes) {
  15646. var mesh = meshes[i];
  15647. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15648. if (!minVector) {
  15649. minVector = boundingBox.minimumWorld;
  15650. maxVector = boundingBox.maximumWorld;
  15651. continue;
  15652. }
  15653. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15654. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15655. }
  15656. return {
  15657. min: minVector,
  15658. max: maxVector
  15659. };
  15660. };
  15661. Mesh.Center = function (meshesOrMinMaxVector) {
  15662. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15663. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15664. };
  15665. /**
  15666. * Merge the array of meshes into a single mesh for performance reasons.
  15667. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15668. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15669. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15670. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15671. */
  15672. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15673. if (disposeSource === void 0) { disposeSource = true; }
  15674. if (!allow32BitsIndices) {
  15675. var totalVertices = 0;
  15676. // Counting vertices
  15677. for (var index = 0; index < meshes.length; index++) {
  15678. if (meshes[index]) {
  15679. totalVertices += meshes[index].getTotalVertices();
  15680. if (totalVertices > 65536) {
  15681. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15682. return null;
  15683. }
  15684. }
  15685. }
  15686. }
  15687. // Merge
  15688. var vertexData;
  15689. var otherVertexData;
  15690. var source;
  15691. for (index = 0; index < meshes.length; index++) {
  15692. if (meshes[index]) {
  15693. meshes[index].computeWorldMatrix(true);
  15694. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15695. otherVertexData.transform(meshes[index].getWorldMatrix());
  15696. if (vertexData) {
  15697. vertexData.merge(otherVertexData);
  15698. }
  15699. else {
  15700. vertexData = otherVertexData;
  15701. source = meshes[index];
  15702. }
  15703. }
  15704. }
  15705. if (!meshSubclass) {
  15706. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15707. }
  15708. vertexData.applyToMesh(meshSubclass);
  15709. // Setting properties
  15710. meshSubclass.material = source.material;
  15711. meshSubclass.checkCollisions = source.checkCollisions;
  15712. // Cleaning
  15713. if (disposeSource) {
  15714. for (index = 0; index < meshes.length; index++) {
  15715. if (meshes[index]) {
  15716. meshes[index].dispose();
  15717. }
  15718. }
  15719. }
  15720. return meshSubclass;
  15721. };
  15722. // Consts
  15723. Mesh._FRONTSIDE = 0;
  15724. Mesh._BACKSIDE = 1;
  15725. Mesh._DOUBLESIDE = 2;
  15726. Mesh._DEFAULTSIDE = 0;
  15727. Mesh._NO_CAP = 0;
  15728. Mesh._CAP_START = 1;
  15729. Mesh._CAP_END = 2;
  15730. Mesh._CAP_ALL = 3;
  15731. return Mesh;
  15732. })(BABYLON.AbstractMesh);
  15733. BABYLON.Mesh = Mesh;
  15734. })(BABYLON || (BABYLON = {}));
  15735. //# sourceMappingURL=babylon.mesh.js.map
  15736. var BABYLON;
  15737. (function (BABYLON) {
  15738. var SubMesh = (function () {
  15739. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15740. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15741. this.materialIndex = materialIndex;
  15742. this.verticesStart = verticesStart;
  15743. this.verticesCount = verticesCount;
  15744. this.indexStart = indexStart;
  15745. this.indexCount = indexCount;
  15746. this._renderId = 0;
  15747. this._mesh = mesh;
  15748. this._renderingMesh = renderingMesh || mesh;
  15749. mesh.subMeshes.push(this);
  15750. this._trianglePlanes = [];
  15751. this._id = mesh.subMeshes.length - 1;
  15752. if (createBoundingBox) {
  15753. this.refreshBoundingInfo();
  15754. mesh.computeWorldMatrix(true);
  15755. }
  15756. }
  15757. SubMesh.prototype.getBoundingInfo = function () {
  15758. return this._boundingInfo;
  15759. };
  15760. SubMesh.prototype.getMesh = function () {
  15761. return this._mesh;
  15762. };
  15763. SubMesh.prototype.getRenderingMesh = function () {
  15764. return this._renderingMesh;
  15765. };
  15766. SubMesh.prototype.getMaterial = function () {
  15767. var rootMaterial = this._renderingMesh.material;
  15768. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15769. var multiMaterial = rootMaterial;
  15770. return multiMaterial.getSubMaterial(this.materialIndex);
  15771. }
  15772. if (!rootMaterial) {
  15773. return this._mesh.getScene().defaultMaterial;
  15774. }
  15775. return rootMaterial;
  15776. };
  15777. // Methods
  15778. SubMesh.prototype.refreshBoundingInfo = function () {
  15779. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15780. if (!data) {
  15781. this._boundingInfo = this._mesh._boundingInfo;
  15782. return;
  15783. }
  15784. var indices = this._renderingMesh.getIndices();
  15785. var extend;
  15786. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15787. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  15788. }
  15789. else {
  15790. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15791. }
  15792. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15793. };
  15794. SubMesh.prototype._checkCollision = function (collider) {
  15795. return this._boundingInfo._checkCollision(collider);
  15796. };
  15797. SubMesh.prototype.updateBoundingInfo = function (world) {
  15798. if (!this._boundingInfo) {
  15799. this.refreshBoundingInfo();
  15800. }
  15801. this._boundingInfo._update(world);
  15802. };
  15803. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15804. return this._boundingInfo.isInFrustum(frustumPlanes);
  15805. };
  15806. SubMesh.prototype.render = function () {
  15807. this._renderingMesh.render(this);
  15808. };
  15809. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15810. if (!this._linesIndexBuffer) {
  15811. var linesIndices = [];
  15812. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15813. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15814. }
  15815. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15816. this.linesIndexCount = linesIndices.length;
  15817. }
  15818. return this._linesIndexBuffer;
  15819. };
  15820. SubMesh.prototype.canIntersects = function (ray) {
  15821. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15822. };
  15823. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15824. var intersectInfo = null;
  15825. // Triangles test
  15826. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15827. var p0 = positions[indices[index]];
  15828. var p1 = positions[indices[index + 1]];
  15829. var p2 = positions[indices[index + 2]];
  15830. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15831. if (currentIntersectInfo) {
  15832. if (currentIntersectInfo.distance < 0) {
  15833. continue;
  15834. }
  15835. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15836. intersectInfo = currentIntersectInfo;
  15837. intersectInfo.faceId = index / 3;
  15838. if (fastCheck) {
  15839. break;
  15840. }
  15841. }
  15842. }
  15843. }
  15844. return intersectInfo;
  15845. };
  15846. // Clone
  15847. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15848. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15849. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15850. return result;
  15851. };
  15852. // Dispose
  15853. SubMesh.prototype.dispose = function () {
  15854. if (this._linesIndexBuffer) {
  15855. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15856. this._linesIndexBuffer = null;
  15857. }
  15858. // Remove from mesh
  15859. var index = this._mesh.subMeshes.indexOf(this);
  15860. this._mesh.subMeshes.splice(index, 1);
  15861. };
  15862. // Statics
  15863. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15864. var minVertexIndex = Number.MAX_VALUE;
  15865. var maxVertexIndex = -Number.MAX_VALUE;
  15866. renderingMesh = renderingMesh || mesh;
  15867. var indices = renderingMesh.getIndices();
  15868. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15869. var vertexIndex = indices[index];
  15870. if (vertexIndex < minVertexIndex)
  15871. minVertexIndex = vertexIndex;
  15872. if (vertexIndex > maxVertexIndex)
  15873. maxVertexIndex = vertexIndex;
  15874. }
  15875. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15876. };
  15877. return SubMesh;
  15878. })();
  15879. BABYLON.SubMesh = SubMesh;
  15880. })(BABYLON || (BABYLON = {}));
  15881. //# sourceMappingURL=babylon.subMesh.js.map
  15882. var BABYLON;
  15883. (function (BABYLON) {
  15884. var BaseTexture = (function () {
  15885. function BaseTexture(scene) {
  15886. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15887. this.hasAlpha = false;
  15888. this.getAlphaFromRGB = false;
  15889. this.level = 1;
  15890. this.isCube = false;
  15891. this.isRenderTarget = false;
  15892. this.animations = new Array();
  15893. this.coordinatesIndex = 0;
  15894. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  15895. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15896. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15897. this.anisotropicFilteringLevel = 4;
  15898. this._scene = scene;
  15899. this._scene.textures.push(this);
  15900. }
  15901. BaseTexture.prototype.getScene = function () {
  15902. return this._scene;
  15903. };
  15904. BaseTexture.prototype.getTextureMatrix = function () {
  15905. return null;
  15906. };
  15907. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  15908. return null;
  15909. };
  15910. BaseTexture.prototype.getInternalTexture = function () {
  15911. return this._texture;
  15912. };
  15913. BaseTexture.prototype.isReady = function () {
  15914. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15915. return true;
  15916. }
  15917. if (this._texture) {
  15918. return this._texture.isReady;
  15919. }
  15920. return false;
  15921. };
  15922. BaseTexture.prototype.getSize = function () {
  15923. if (this._texture._width) {
  15924. return { width: this._texture._width, height: this._texture._height };
  15925. }
  15926. if (this._texture._size) {
  15927. return { width: this._texture._size, height: this._texture._size };
  15928. }
  15929. return { width: 0, height: 0 };
  15930. };
  15931. BaseTexture.prototype.getBaseSize = function () {
  15932. if (!this.isReady())
  15933. return { width: 0, height: 0 };
  15934. if (this._texture._size) {
  15935. return { width: this._texture._size, height: this._texture._size };
  15936. }
  15937. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  15938. };
  15939. BaseTexture.prototype.scale = function (ratio) {
  15940. };
  15941. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  15942. get: function () {
  15943. return false;
  15944. },
  15945. enumerable: true,
  15946. configurable: true
  15947. });
  15948. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  15949. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15950. for (var index = 0; index < texturesCache.length; index++) {
  15951. var texturesCacheEntry = texturesCache[index];
  15952. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15953. texturesCache.splice(index, 1);
  15954. return;
  15955. }
  15956. }
  15957. };
  15958. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  15959. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15960. for (var index = 0; index < texturesCache.length; index++) {
  15961. var texturesCacheEntry = texturesCache[index];
  15962. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15963. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  15964. texturesCacheEntry.references++;
  15965. return texturesCacheEntry;
  15966. }
  15967. }
  15968. }
  15969. return null;
  15970. };
  15971. BaseTexture.prototype.delayLoad = function () {
  15972. };
  15973. BaseTexture.prototype.releaseInternalTexture = function () {
  15974. if (!this._texture) {
  15975. return;
  15976. }
  15977. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15978. this._texture.references--;
  15979. // Final reference ?
  15980. if (this._texture.references === 0) {
  15981. var index = texturesCache.indexOf(this._texture);
  15982. texturesCache.splice(index, 1);
  15983. this._scene.getEngine()._releaseTexture(this._texture);
  15984. delete this._texture;
  15985. }
  15986. };
  15987. BaseTexture.prototype.clone = function () {
  15988. return null;
  15989. };
  15990. BaseTexture.prototype.dispose = function () {
  15991. // Remove from scene
  15992. var index = this._scene.textures.indexOf(this);
  15993. if (index >= 0) {
  15994. this._scene.textures.splice(index, 1);
  15995. }
  15996. if (this._texture === undefined) {
  15997. return;
  15998. }
  15999. this.releaseInternalTexture();
  16000. // Callback
  16001. if (this.onDispose) {
  16002. this.onDispose();
  16003. }
  16004. };
  16005. return BaseTexture;
  16006. })();
  16007. BABYLON.BaseTexture = BaseTexture;
  16008. })(BABYLON || (BABYLON = {}));
  16009. //# sourceMappingURL=babylon.baseTexture.js.map
  16010. var __extends = this.__extends || function (d, b) {
  16011. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16012. function __() { this.constructor = d; }
  16013. __.prototype = b.prototype;
  16014. d.prototype = new __();
  16015. };
  16016. var BABYLON;
  16017. (function (BABYLON) {
  16018. var Texture = (function (_super) {
  16019. __extends(Texture, _super);
  16020. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16021. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16022. if (onLoad === void 0) { onLoad = null; }
  16023. if (onError === void 0) { onError = null; }
  16024. if (buffer === void 0) { buffer = null; }
  16025. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16026. _super.call(this, scene);
  16027. this.uOffset = 0;
  16028. this.vOffset = 0;
  16029. this.uScale = 1.0;
  16030. this.vScale = 1.0;
  16031. this.uAng = 0;
  16032. this.vAng = 0;
  16033. this.wAng = 0;
  16034. this.name = url;
  16035. this.url = url;
  16036. this._noMipmap = noMipmap;
  16037. this._invertY = invertY;
  16038. this._samplingMode = samplingMode;
  16039. this._buffer = buffer;
  16040. this._deleteBuffer = deleteBuffer;
  16041. if (!url) {
  16042. return;
  16043. }
  16044. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16045. if (!this._texture) {
  16046. if (!scene.useDelayedTextureLoading) {
  16047. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16048. if (deleteBuffer) {
  16049. delete this._buffer;
  16050. }
  16051. }
  16052. else {
  16053. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16054. }
  16055. }
  16056. else {
  16057. BABYLON.Tools.SetImmediate(function () {
  16058. if (onLoad) {
  16059. onLoad();
  16060. }
  16061. });
  16062. }
  16063. }
  16064. Texture.prototype.delayLoad = function () {
  16065. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16066. return;
  16067. }
  16068. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16069. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16070. if (!this._texture) {
  16071. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16072. if (this._deleteBuffer) {
  16073. delete this._buffer;
  16074. }
  16075. }
  16076. };
  16077. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16078. if (!this._texture) {
  16079. return;
  16080. }
  16081. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16082. };
  16083. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16084. x -= this.uOffset + 0.5;
  16085. y -= this.vOffset + 0.5;
  16086. z -= 0.5;
  16087. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16088. t.x *= this.uScale;
  16089. t.y *= this.vScale;
  16090. t.x += 0.5;
  16091. t.y += 0.5;
  16092. t.z += 0.5;
  16093. };
  16094. Texture.prototype.getTextureMatrix = function () {
  16095. if (this.uOffset === this._cachedUOffset &&
  16096. this.vOffset === this._cachedVOffset &&
  16097. this.uScale === this._cachedUScale &&
  16098. this.vScale === this._cachedVScale &&
  16099. this.uAng === this._cachedUAng &&
  16100. this.vAng === this._cachedVAng &&
  16101. this.wAng === this._cachedWAng) {
  16102. return this._cachedTextureMatrix;
  16103. }
  16104. this._cachedUOffset = this.uOffset;
  16105. this._cachedVOffset = this.vOffset;
  16106. this._cachedUScale = this.uScale;
  16107. this._cachedVScale = this.vScale;
  16108. this._cachedUAng = this.uAng;
  16109. this._cachedVAng = this.vAng;
  16110. this._cachedWAng = this.wAng;
  16111. if (!this._cachedTextureMatrix) {
  16112. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16113. this._rowGenerationMatrix = new BABYLON.Matrix();
  16114. this._t0 = BABYLON.Vector3.Zero();
  16115. this._t1 = BABYLON.Vector3.Zero();
  16116. this._t2 = BABYLON.Vector3.Zero();
  16117. }
  16118. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16119. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16120. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16121. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16122. this._t1.subtractInPlace(this._t0);
  16123. this._t2.subtractInPlace(this._t0);
  16124. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16125. this._cachedTextureMatrix.m[0] = this._t1.x;
  16126. this._cachedTextureMatrix.m[1] = this._t1.y;
  16127. this._cachedTextureMatrix.m[2] = this._t1.z;
  16128. this._cachedTextureMatrix.m[4] = this._t2.x;
  16129. this._cachedTextureMatrix.m[5] = this._t2.y;
  16130. this._cachedTextureMatrix.m[6] = this._t2.z;
  16131. this._cachedTextureMatrix.m[8] = this._t0.x;
  16132. this._cachedTextureMatrix.m[9] = this._t0.y;
  16133. this._cachedTextureMatrix.m[10] = this._t0.z;
  16134. return this._cachedTextureMatrix;
  16135. };
  16136. Texture.prototype.getReflectionTextureMatrix = function () {
  16137. if (this.uOffset === this._cachedUOffset &&
  16138. this.vOffset === this._cachedVOffset &&
  16139. this.uScale === this._cachedUScale &&
  16140. this.vScale === this._cachedVScale &&
  16141. this.coordinatesMode === this._cachedCoordinatesMode) {
  16142. return this._cachedTextureMatrix;
  16143. }
  16144. if (!this._cachedTextureMatrix) {
  16145. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16146. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16147. }
  16148. this._cachedCoordinatesMode = this.coordinatesMode;
  16149. switch (this.coordinatesMode) {
  16150. case Texture.SPHERICAL_MODE:
  16151. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16152. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16153. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16154. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16155. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16156. break;
  16157. case Texture.PLANAR_MODE:
  16158. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16159. this._cachedTextureMatrix[0] = this.uScale;
  16160. this._cachedTextureMatrix[5] = this.vScale;
  16161. this._cachedTextureMatrix[12] = this.uOffset;
  16162. this._cachedTextureMatrix[13] = this.vOffset;
  16163. break;
  16164. case Texture.PROJECTION_MODE:
  16165. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16166. this._projectionModeMatrix.m[0] = 0.5;
  16167. this._projectionModeMatrix.m[5] = -0.5;
  16168. this._projectionModeMatrix.m[10] = 0.0;
  16169. this._projectionModeMatrix.m[12] = 0.5;
  16170. this._projectionModeMatrix.m[13] = 0.5;
  16171. this._projectionModeMatrix.m[14] = 1.0;
  16172. this._projectionModeMatrix.m[15] = 1.0;
  16173. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16174. break;
  16175. default:
  16176. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16177. break;
  16178. }
  16179. return this._cachedTextureMatrix;
  16180. };
  16181. Texture.prototype.clone = function () {
  16182. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16183. // Base texture
  16184. newTexture.hasAlpha = this.hasAlpha;
  16185. newTexture.level = this.level;
  16186. newTexture.wrapU = this.wrapU;
  16187. newTexture.wrapV = this.wrapV;
  16188. newTexture.coordinatesIndex = this.coordinatesIndex;
  16189. newTexture.coordinatesMode = this.coordinatesMode;
  16190. // Texture
  16191. newTexture.uOffset = this.uOffset;
  16192. newTexture.vOffset = this.vOffset;
  16193. newTexture.uScale = this.uScale;
  16194. newTexture.vScale = this.vScale;
  16195. newTexture.uAng = this.uAng;
  16196. newTexture.vAng = this.vAng;
  16197. newTexture.wAng = this.wAng;
  16198. return newTexture;
  16199. };
  16200. // Statics
  16201. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16202. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16203. if (onLoad === void 0) { onLoad = null; }
  16204. if (onError === void 0) { onError = null; }
  16205. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16206. };
  16207. // Constants
  16208. Texture.NEAREST_SAMPLINGMODE = 1;
  16209. Texture.BILINEAR_SAMPLINGMODE = 2;
  16210. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16211. Texture.EXPLICIT_MODE = 0;
  16212. Texture.SPHERICAL_MODE = 1;
  16213. Texture.PLANAR_MODE = 2;
  16214. Texture.CUBIC_MODE = 3;
  16215. Texture.PROJECTION_MODE = 4;
  16216. Texture.SKYBOX_MODE = 5;
  16217. Texture.CLAMP_ADDRESSMODE = 0;
  16218. Texture.WRAP_ADDRESSMODE = 1;
  16219. Texture.MIRROR_ADDRESSMODE = 2;
  16220. return Texture;
  16221. })(BABYLON.BaseTexture);
  16222. BABYLON.Texture = Texture;
  16223. })(BABYLON || (BABYLON = {}));
  16224. //# sourceMappingURL=babylon.texture.js.map
  16225. var __extends = this.__extends || function (d, b) {
  16226. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16227. function __() { this.constructor = d; }
  16228. __.prototype = b.prototype;
  16229. d.prototype = new __();
  16230. };
  16231. var BABYLON;
  16232. (function (BABYLON) {
  16233. var CubeTexture = (function (_super) {
  16234. __extends(CubeTexture, _super);
  16235. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16236. _super.call(this, scene);
  16237. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16238. this.name = rootUrl;
  16239. this.url = rootUrl;
  16240. this._noMipmap = noMipmap;
  16241. this.hasAlpha = false;
  16242. this._texture = this._getFromCache(rootUrl, noMipmap);
  16243. if (!extensions) {
  16244. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16245. }
  16246. this._extensions = extensions;
  16247. if (!this._texture) {
  16248. if (!scene.useDelayedTextureLoading) {
  16249. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16250. }
  16251. else {
  16252. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16253. }
  16254. }
  16255. this.isCube = true;
  16256. this._textureMatrix = BABYLON.Matrix.Identity();
  16257. }
  16258. CubeTexture.prototype.clone = function () {
  16259. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16260. // Base texture
  16261. newTexture.level = this.level;
  16262. newTexture.wrapU = this.wrapU;
  16263. newTexture.wrapV = this.wrapV;
  16264. newTexture.coordinatesIndex = this.coordinatesIndex;
  16265. newTexture.coordinatesMode = this.coordinatesMode;
  16266. return newTexture;
  16267. };
  16268. // Methods
  16269. CubeTexture.prototype.delayLoad = function () {
  16270. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16271. return;
  16272. }
  16273. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16274. this._texture = this._getFromCache(this.url, this._noMipmap);
  16275. if (!this._texture) {
  16276. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16277. }
  16278. };
  16279. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16280. return this._textureMatrix;
  16281. };
  16282. return CubeTexture;
  16283. })(BABYLON.BaseTexture);
  16284. BABYLON.CubeTexture = CubeTexture;
  16285. })(BABYLON || (BABYLON = {}));
  16286. //# sourceMappingURL=babylon.cubeTexture.js.map
  16287. var __extends = this.__extends || function (d, b) {
  16288. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16289. function __() { this.constructor = d; }
  16290. __.prototype = b.prototype;
  16291. d.prototype = new __();
  16292. };
  16293. var BABYLON;
  16294. (function (BABYLON) {
  16295. var RenderTargetTexture = (function (_super) {
  16296. __extends(RenderTargetTexture, _super);
  16297. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16298. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16299. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16300. _super.call(this, null, scene, !generateMipMaps);
  16301. this.renderList = new Array();
  16302. this.renderParticles = true;
  16303. this.renderSprites = false;
  16304. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16305. this._currentRefreshId = -1;
  16306. this._refreshRate = 1;
  16307. this.name = name;
  16308. this.isRenderTarget = true;
  16309. this._size = size;
  16310. this._generateMipMaps = generateMipMaps;
  16311. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16312. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16313. // Rendering groups
  16314. this._renderingManager = new BABYLON.RenderingManager(scene);
  16315. }
  16316. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16317. this._currentRefreshId = -1;
  16318. };
  16319. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16320. get: function () {
  16321. return this._refreshRate;
  16322. },
  16323. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16324. set: function (value) {
  16325. this._refreshRate = value;
  16326. this.resetRefreshCounter();
  16327. },
  16328. enumerable: true,
  16329. configurable: true
  16330. });
  16331. RenderTargetTexture.prototype._shouldRender = function () {
  16332. if (this._currentRefreshId === -1) {
  16333. this._currentRefreshId = 1;
  16334. return true;
  16335. }
  16336. if (this.refreshRate === this._currentRefreshId) {
  16337. this._currentRefreshId = 1;
  16338. return true;
  16339. }
  16340. this._currentRefreshId++;
  16341. return false;
  16342. };
  16343. RenderTargetTexture.prototype.isReady = function () {
  16344. if (!this.getScene().renderTargetsEnabled) {
  16345. return false;
  16346. }
  16347. return _super.prototype.isReady.call(this);
  16348. };
  16349. RenderTargetTexture.prototype.getRenderSize = function () {
  16350. return this._size;
  16351. };
  16352. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16353. get: function () {
  16354. return true;
  16355. },
  16356. enumerable: true,
  16357. configurable: true
  16358. });
  16359. RenderTargetTexture.prototype.scale = function (ratio) {
  16360. var newSize = this._size * ratio;
  16361. this.resize(newSize, this._generateMipMaps);
  16362. };
  16363. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16364. this.releaseInternalTexture();
  16365. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16366. };
  16367. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16368. var scene = this.getScene();
  16369. var engine = scene.getEngine();
  16370. if (this._waitingRenderList) {
  16371. this.renderList = [];
  16372. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16373. var id = this._waitingRenderList[index];
  16374. this.renderList.push(scene.getMeshByID(id));
  16375. }
  16376. delete this._waitingRenderList;
  16377. }
  16378. if (this.renderList && this.renderList.length === 0) {
  16379. return;
  16380. }
  16381. // Bind
  16382. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16383. engine.bindFramebuffer(this._texture);
  16384. }
  16385. this._renderingManager.reset();
  16386. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16387. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16388. var mesh = currentRenderList[meshIndex];
  16389. if (mesh) {
  16390. if (!mesh.isReady()) {
  16391. // Reset _currentRefreshId
  16392. this.resetRefreshCounter();
  16393. continue;
  16394. }
  16395. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16396. mesh._activate(scene.getRenderId());
  16397. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16398. var subMesh = mesh.subMeshes[subIndex];
  16399. scene._activeIndices += subMesh.indexCount;
  16400. this._renderingManager.dispatch(subMesh);
  16401. }
  16402. }
  16403. }
  16404. }
  16405. if (this.onBeforeRender) {
  16406. this.onBeforeRender();
  16407. }
  16408. // Clear
  16409. if (this.onClear) {
  16410. this.onClear(engine);
  16411. }
  16412. else {
  16413. engine.clear(scene.clearColor, true, true);
  16414. }
  16415. if (!this._doNotChangeAspectRatio) {
  16416. scene.updateTransformMatrix(true);
  16417. }
  16418. // Render
  16419. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16420. if (useCameraPostProcess) {
  16421. scene.postProcessManager._finalizeFrame(false, this._texture);
  16422. }
  16423. if (!this._doNotChangeAspectRatio) {
  16424. scene.updateTransformMatrix(true);
  16425. }
  16426. if (this.onAfterRender) {
  16427. this.onAfterRender();
  16428. }
  16429. // Dump ?
  16430. if (dumpForDebug) {
  16431. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16432. }
  16433. // Unbind
  16434. engine.unBindFramebuffer(this._texture);
  16435. if (this.onAfterUnbind) {
  16436. this.onAfterUnbind();
  16437. }
  16438. };
  16439. RenderTargetTexture.prototype.clone = function () {
  16440. var textureSize = this.getSize();
  16441. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16442. // Base texture
  16443. newTexture.hasAlpha = this.hasAlpha;
  16444. newTexture.level = this.level;
  16445. // RenderTarget Texture
  16446. newTexture.coordinatesMode = this.coordinatesMode;
  16447. newTexture.renderList = this.renderList.slice(0);
  16448. return newTexture;
  16449. };
  16450. return RenderTargetTexture;
  16451. })(BABYLON.Texture);
  16452. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16453. })(BABYLON || (BABYLON = {}));
  16454. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  16455. var __extends = this.__extends || function (d, b) {
  16456. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16457. function __() { this.constructor = d; }
  16458. __.prototype = b.prototype;
  16459. d.prototype = new __();
  16460. };
  16461. var BABYLON;
  16462. (function (BABYLON) {
  16463. var ProceduralTexture = (function (_super) {
  16464. __extends(ProceduralTexture, _super);
  16465. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16466. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16467. _super.call(this, null, scene, !generateMipMaps);
  16468. this._currentRefreshId = -1;
  16469. this._refreshRate = 1;
  16470. this._vertexDeclaration = [2];
  16471. this._vertexStrideSize = 2 * 4;
  16472. this._uniforms = new Array();
  16473. this._samplers = new Array();
  16474. this._textures = new Array();
  16475. this._floats = new Array();
  16476. this._floatsArrays = {};
  16477. this._colors3 = new Array();
  16478. this._colors4 = new Array();
  16479. this._vectors2 = new Array();
  16480. this._vectors3 = new Array();
  16481. this._matrices = new Array();
  16482. this._fallbackTextureUsed = false;
  16483. scene._proceduralTextures.push(this);
  16484. this.name = name;
  16485. this.isRenderTarget = true;
  16486. this._size = size;
  16487. this._generateMipMaps = generateMipMaps;
  16488. this.setFragment(fragment);
  16489. this._fallbackTexture = fallbackTexture;
  16490. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16491. // VBO
  16492. var vertices = [];
  16493. vertices.push(1, 1);
  16494. vertices.push(-1, 1);
  16495. vertices.push(-1, -1);
  16496. vertices.push(1, -1);
  16497. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16498. // Indices
  16499. var indices = [];
  16500. indices.push(0);
  16501. indices.push(1);
  16502. indices.push(2);
  16503. indices.push(0);
  16504. indices.push(2);
  16505. indices.push(3);
  16506. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16507. }
  16508. ProceduralTexture.prototype.reset = function () {
  16509. if (this._effect === undefined) {
  16510. return;
  16511. }
  16512. var engine = this.getScene().getEngine();
  16513. engine._releaseEffect(this._effect);
  16514. };
  16515. ProceduralTexture.prototype.isReady = function () {
  16516. var _this = this;
  16517. var engine = this.getScene().getEngine();
  16518. var shaders;
  16519. if (!this._fragment) {
  16520. return false;
  16521. }
  16522. if (this._fallbackTextureUsed) {
  16523. return true;
  16524. }
  16525. if (this._fragment.fragmentElement !== undefined) {
  16526. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16527. }
  16528. else {
  16529. shaders = { vertex: "procedural", fragment: this._fragment };
  16530. }
  16531. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16532. _this.releaseInternalTexture();
  16533. if (_this._fallbackTexture) {
  16534. _this._texture = _this._fallbackTexture._texture;
  16535. _this._texture.references++;
  16536. }
  16537. _this._fallbackTextureUsed = true;
  16538. });
  16539. return this._effect.isReady();
  16540. };
  16541. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16542. this._currentRefreshId = -1;
  16543. };
  16544. ProceduralTexture.prototype.setFragment = function (fragment) {
  16545. this._fragment = fragment;
  16546. };
  16547. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16548. get: function () {
  16549. return this._refreshRate;
  16550. },
  16551. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16552. set: function (value) {
  16553. this._refreshRate = value;
  16554. this.resetRefreshCounter();
  16555. },
  16556. enumerable: true,
  16557. configurable: true
  16558. });
  16559. ProceduralTexture.prototype._shouldRender = function () {
  16560. if (!this.isReady() || !this._texture) {
  16561. return false;
  16562. }
  16563. if (this._fallbackTextureUsed) {
  16564. return false;
  16565. }
  16566. if (this._currentRefreshId === -1) {
  16567. this._currentRefreshId = 1;
  16568. return true;
  16569. }
  16570. if (this.refreshRate === this._currentRefreshId) {
  16571. this._currentRefreshId = 1;
  16572. return true;
  16573. }
  16574. this._currentRefreshId++;
  16575. return false;
  16576. };
  16577. ProceduralTexture.prototype.getRenderSize = function () {
  16578. return this._size;
  16579. };
  16580. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16581. if (this._fallbackTextureUsed) {
  16582. return;
  16583. }
  16584. this.releaseInternalTexture();
  16585. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16586. };
  16587. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16588. if (this._uniforms.indexOf(uniformName) === -1) {
  16589. this._uniforms.push(uniformName);
  16590. }
  16591. };
  16592. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16593. if (this._samplers.indexOf(name) === -1) {
  16594. this._samplers.push(name);
  16595. }
  16596. this._textures[name] = texture;
  16597. return this;
  16598. };
  16599. ProceduralTexture.prototype.setFloat = function (name, value) {
  16600. this._checkUniform(name);
  16601. this._floats[name] = value;
  16602. return this;
  16603. };
  16604. ProceduralTexture.prototype.setFloats = function (name, value) {
  16605. this._checkUniform(name);
  16606. this._floatsArrays[name] = value;
  16607. return this;
  16608. };
  16609. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16610. this._checkUniform(name);
  16611. this._colors3[name] = value;
  16612. return this;
  16613. };
  16614. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16615. this._checkUniform(name);
  16616. this._colors4[name] = value;
  16617. return this;
  16618. };
  16619. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16620. this._checkUniform(name);
  16621. this._vectors2[name] = value;
  16622. return this;
  16623. };
  16624. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16625. this._checkUniform(name);
  16626. this._vectors3[name] = value;
  16627. return this;
  16628. };
  16629. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16630. this._checkUniform(name);
  16631. this._matrices[name] = value;
  16632. return this;
  16633. };
  16634. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16635. var scene = this.getScene();
  16636. var engine = scene.getEngine();
  16637. engine.bindFramebuffer(this._texture);
  16638. // Clear
  16639. engine.clear(scene.clearColor, true, true);
  16640. // Render
  16641. engine.enableEffect(this._effect);
  16642. engine.setState(false);
  16643. // Texture
  16644. for (var name in this._textures) {
  16645. this._effect.setTexture(name, this._textures[name]);
  16646. }
  16647. // Float
  16648. for (name in this._floats) {
  16649. this._effect.setFloat(name, this._floats[name]);
  16650. }
  16651. // Floats
  16652. for (name in this._floatsArrays) {
  16653. this._effect.setArray(name, this._floatsArrays[name]);
  16654. }
  16655. // Color3
  16656. for (name in this._colors3) {
  16657. this._effect.setColor3(name, this._colors3[name]);
  16658. }
  16659. // Color4
  16660. for (name in this._colors4) {
  16661. var color = this._colors4[name];
  16662. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16663. }
  16664. // Vector2
  16665. for (name in this._vectors2) {
  16666. this._effect.setVector2(name, this._vectors2[name]);
  16667. }
  16668. // Vector3
  16669. for (name in this._vectors3) {
  16670. this._effect.setVector3(name, this._vectors3[name]);
  16671. }
  16672. // Matrix
  16673. for (name in this._matrices) {
  16674. this._effect.setMatrix(name, this._matrices[name]);
  16675. }
  16676. // VBOs
  16677. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16678. // Draw order
  16679. engine.draw(true, 0, 6);
  16680. // Unbind
  16681. engine.unBindFramebuffer(this._texture);
  16682. };
  16683. ProceduralTexture.prototype.clone = function () {
  16684. var textureSize = this.getSize();
  16685. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16686. // Base texture
  16687. newTexture.hasAlpha = this.hasAlpha;
  16688. newTexture.level = this.level;
  16689. // RenderTarget Texture
  16690. newTexture.coordinatesMode = this.coordinatesMode;
  16691. return newTexture;
  16692. };
  16693. ProceduralTexture.prototype.dispose = function () {
  16694. var index = this.getScene()._proceduralTextures.indexOf(this);
  16695. if (index >= 0) {
  16696. this.getScene()._proceduralTextures.splice(index, 1);
  16697. }
  16698. _super.prototype.dispose.call(this);
  16699. };
  16700. return ProceduralTexture;
  16701. })(BABYLON.Texture);
  16702. BABYLON.ProceduralTexture = ProceduralTexture;
  16703. })(BABYLON || (BABYLON = {}));
  16704. //# sourceMappingURL=babylon.proceduralTexture.js.map
  16705. var __extends = this.__extends || function (d, b) {
  16706. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16707. function __() { this.constructor = d; }
  16708. __.prototype = b.prototype;
  16709. d.prototype = new __();
  16710. };
  16711. var BABYLON;
  16712. (function (BABYLON) {
  16713. var MirrorTexture = (function (_super) {
  16714. __extends(MirrorTexture, _super);
  16715. function MirrorTexture(name, size, scene, generateMipMaps) {
  16716. var _this = this;
  16717. _super.call(this, name, size, scene, generateMipMaps, true);
  16718. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16719. this._transformMatrix = BABYLON.Matrix.Zero();
  16720. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16721. this.onBeforeRender = function () {
  16722. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16723. _this._savedViewMatrix = scene.getViewMatrix();
  16724. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16725. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16726. scene.clipPlane = _this.mirrorPlane;
  16727. scene.getEngine().cullBackFaces = false;
  16728. };
  16729. this.onAfterRender = function () {
  16730. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16731. scene.getEngine().cullBackFaces = true;
  16732. delete scene.clipPlane;
  16733. };
  16734. }
  16735. MirrorTexture.prototype.clone = function () {
  16736. var textureSize = this.getSize();
  16737. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16738. // Base texture
  16739. newTexture.hasAlpha = this.hasAlpha;
  16740. newTexture.level = this.level;
  16741. // Mirror Texture
  16742. newTexture.mirrorPlane = this.mirrorPlane.clone();
  16743. newTexture.renderList = this.renderList.slice(0);
  16744. return newTexture;
  16745. };
  16746. return MirrorTexture;
  16747. })(BABYLON.RenderTargetTexture);
  16748. BABYLON.MirrorTexture = MirrorTexture;
  16749. })(BABYLON || (BABYLON = {}));
  16750. //# sourceMappingURL=babylon.mirrorTexture.js.map
  16751. var __extends = this.__extends || function (d, b) {
  16752. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16753. function __() { this.constructor = d; }
  16754. __.prototype = b.prototype;
  16755. d.prototype = new __();
  16756. };
  16757. var BABYLON;
  16758. (function (BABYLON) {
  16759. var DynamicTexture = (function (_super) {
  16760. __extends(DynamicTexture, _super);
  16761. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  16762. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16763. _super.call(this, null, scene, !generateMipMaps);
  16764. this.name = name;
  16765. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16766. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16767. this._generateMipMaps = generateMipMaps;
  16768. if (options.getContext) {
  16769. this._canvas = options;
  16770. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16771. }
  16772. else {
  16773. this._canvas = document.createElement("canvas");
  16774. if (options.width) {
  16775. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16776. }
  16777. else {
  16778. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  16779. }
  16780. }
  16781. var textureSize = this.getSize();
  16782. this._canvas.width = textureSize.width;
  16783. this._canvas.height = textureSize.height;
  16784. this._context = this._canvas.getContext("2d");
  16785. }
  16786. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  16787. get: function () {
  16788. return true;
  16789. },
  16790. enumerable: true,
  16791. configurable: true
  16792. });
  16793. DynamicTexture.prototype.scale = function (ratio) {
  16794. var textureSize = this.getSize();
  16795. textureSize.width *= ratio;
  16796. textureSize.height *= ratio;
  16797. this._canvas.width = textureSize.width;
  16798. this._canvas.height = textureSize.height;
  16799. this.releaseInternalTexture();
  16800. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  16801. };
  16802. DynamicTexture.prototype.getContext = function () {
  16803. return this._context;
  16804. };
  16805. DynamicTexture.prototype.clear = function () {
  16806. var size = this.getSize();
  16807. this._context.fillRect(0, 0, size.width, size.height);
  16808. };
  16809. DynamicTexture.prototype.update = function (invertY) {
  16810. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  16811. };
  16812. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  16813. if (update === void 0) { update = true; }
  16814. var size = this.getSize();
  16815. if (clearColor) {
  16816. this._context.fillStyle = clearColor;
  16817. this._context.fillRect(0, 0, size.width, size.height);
  16818. }
  16819. this._context.font = font;
  16820. if (x === null) {
  16821. var textSize = this._context.measureText(text);
  16822. x = (size.width - textSize.width) / 2;
  16823. }
  16824. this._context.fillStyle = color;
  16825. this._context.fillText(text, x, y);
  16826. if (update) {
  16827. this.update(invertY);
  16828. }
  16829. };
  16830. DynamicTexture.prototype.clone = function () {
  16831. var textureSize = this.getSize();
  16832. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16833. // Base texture
  16834. newTexture.hasAlpha = this.hasAlpha;
  16835. newTexture.level = this.level;
  16836. // Dynamic Texture
  16837. newTexture.wrapU = this.wrapU;
  16838. newTexture.wrapV = this.wrapV;
  16839. return newTexture;
  16840. };
  16841. return DynamicTexture;
  16842. })(BABYLON.Texture);
  16843. BABYLON.DynamicTexture = DynamicTexture;
  16844. })(BABYLON || (BABYLON = {}));
  16845. //# sourceMappingURL=babylon.dynamicTexture.js.map
  16846. var __extends = this.__extends || function (d, b) {
  16847. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16848. function __() { this.constructor = d; }
  16849. __.prototype = b.prototype;
  16850. d.prototype = new __();
  16851. };
  16852. var BABYLON;
  16853. (function (BABYLON) {
  16854. var VideoTexture = (function (_super) {
  16855. __extends(VideoTexture, _super);
  16856. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  16857. var _this = this;
  16858. if (generateMipMaps === void 0) { generateMipMaps = false; }
  16859. if (invertY === void 0) { invertY = true; }
  16860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16861. _super.call(this, null, scene, !generateMipMaps, invertY);
  16862. this._autoLaunch = true;
  16863. this.name = name;
  16864. this.video = document.createElement("video");
  16865. this.video.autoplay = false;
  16866. this.video.loop = true;
  16867. this.video.addEventListener("canplaythrough", function () {
  16868. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  16869. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16870. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16871. }
  16872. else {
  16873. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16874. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16875. generateMipMaps = false;
  16876. }
  16877. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  16878. _this._texture.isReady = true;
  16879. });
  16880. urls.forEach(function (url) {
  16881. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  16882. var source = document.createElement("source");
  16883. source.src = url;
  16884. _this.video.appendChild(source);
  16885. });
  16886. this._lastUpdate = BABYLON.Tools.Now;
  16887. }
  16888. VideoTexture.prototype.update = function () {
  16889. if (this._autoLaunch) {
  16890. this._autoLaunch = false;
  16891. this.video.play();
  16892. }
  16893. var now = BABYLON.Tools.Now;
  16894. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  16895. return false;
  16896. }
  16897. this._lastUpdate = now;
  16898. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  16899. return true;
  16900. };
  16901. return VideoTexture;
  16902. })(BABYLON.Texture);
  16903. BABYLON.VideoTexture = VideoTexture;
  16904. })(BABYLON || (BABYLON = {}));
  16905. //# sourceMappingURL=babylon.videoTexture.js.map
  16906. var __extends = this.__extends || function (d, b) {
  16907. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16908. function __() { this.constructor = d; }
  16909. __.prototype = b.prototype;
  16910. d.prototype = new __();
  16911. };
  16912. var BABYLON;
  16913. (function (BABYLON) {
  16914. var CustomProceduralTexture = (function (_super) {
  16915. __extends(CustomProceduralTexture, _super);
  16916. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  16917. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  16918. this._animate = true;
  16919. this._time = 0;
  16920. this._texturePath = texturePath;
  16921. //Try to load json
  16922. this.loadJson(texturePath);
  16923. this.refreshRate = 1;
  16924. }
  16925. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  16926. var _this = this;
  16927. var that = this;
  16928. function noConfigFile() {
  16929. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  16930. try {
  16931. that.setFragment(that._texturePath);
  16932. }
  16933. catch (ex) {
  16934. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  16935. }
  16936. }
  16937. var configFileUrl = jsonUrl + "/config.json";
  16938. var xhr = new XMLHttpRequest();
  16939. xhr.open("GET", configFileUrl, true);
  16940. xhr.addEventListener("load", function () {
  16941. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  16942. try {
  16943. _this._config = JSON.parse(xhr.response);
  16944. _this.updateShaderUniforms();
  16945. _this.updateTextures();
  16946. _this.setFragment(_this._texturePath + "/custom");
  16947. _this._animate = _this._config.animate;
  16948. _this.refreshRate = _this._config.refreshrate;
  16949. }
  16950. catch (ex) {
  16951. noConfigFile();
  16952. }
  16953. }
  16954. else {
  16955. noConfigFile();
  16956. }
  16957. }, false);
  16958. xhr.addEventListener("error", function () {
  16959. noConfigFile();
  16960. }, false);
  16961. try {
  16962. xhr.send();
  16963. }
  16964. catch (ex) {
  16965. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  16966. }
  16967. };
  16968. CustomProceduralTexture.prototype.isReady = function () {
  16969. if (!_super.prototype.isReady.call(this)) {
  16970. return false;
  16971. }
  16972. for (var name in this._textures) {
  16973. var texture = this._textures[name];
  16974. if (!texture.isReady()) {
  16975. return false;
  16976. }
  16977. }
  16978. return true;
  16979. };
  16980. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16981. if (this._animate) {
  16982. this._time += this.getScene().getAnimationRatio() * 0.03;
  16983. this.updateShaderUniforms();
  16984. }
  16985. _super.prototype.render.call(this, useCameraPostProcess);
  16986. };
  16987. CustomProceduralTexture.prototype.updateTextures = function () {
  16988. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  16989. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  16990. }
  16991. };
  16992. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  16993. if (this._config) {
  16994. for (var j = 0; j < this._config.uniforms.length; j++) {
  16995. var uniform = this._config.uniforms[j];
  16996. switch (uniform.type) {
  16997. case "float":
  16998. this.setFloat(uniform.name, uniform.value);
  16999. break;
  17000. case "color3":
  17001. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17002. break;
  17003. case "color4":
  17004. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17005. break;
  17006. case "vector2":
  17007. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17008. break;
  17009. case "vector3":
  17010. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17011. break;
  17012. }
  17013. }
  17014. }
  17015. this.setFloat("time", this._time);
  17016. };
  17017. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17018. get: function () {
  17019. return this._animate;
  17020. },
  17021. set: function (value) {
  17022. this._animate = value;
  17023. },
  17024. enumerable: true,
  17025. configurable: true
  17026. });
  17027. return CustomProceduralTexture;
  17028. })(BABYLON.ProceduralTexture);
  17029. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17030. })(BABYLON || (BABYLON = {}));
  17031. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  17032. var __extends = this.__extends || function (d, b) {
  17033. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17034. function __() { this.constructor = d; }
  17035. __.prototype = b.prototype;
  17036. d.prototype = new __();
  17037. };
  17038. var BABYLON;
  17039. (function (BABYLON) {
  17040. var WoodProceduralTexture = (function (_super) {
  17041. __extends(WoodProceduralTexture, _super);
  17042. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17043. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17044. this._ampScale = 100.0;
  17045. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17046. this.updateShaderUniforms();
  17047. this.refreshRate = 0;
  17048. }
  17049. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17050. this.setFloat("ampScale", this._ampScale);
  17051. this.setColor3("woodColor", this._woodColor);
  17052. };
  17053. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17054. get: function () {
  17055. return this._ampScale;
  17056. },
  17057. set: function (value) {
  17058. this._ampScale = value;
  17059. this.updateShaderUniforms();
  17060. },
  17061. enumerable: true,
  17062. configurable: true
  17063. });
  17064. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17065. get: function () {
  17066. return this._woodColor;
  17067. },
  17068. set: function (value) {
  17069. this._woodColor = value;
  17070. this.updateShaderUniforms();
  17071. },
  17072. enumerable: true,
  17073. configurable: true
  17074. });
  17075. return WoodProceduralTexture;
  17076. })(BABYLON.ProceduralTexture);
  17077. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17078. var FireProceduralTexture = (function (_super) {
  17079. __extends(FireProceduralTexture, _super);
  17080. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17081. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17082. this._time = 0.0;
  17083. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17084. this._autoGenerateTime = true;
  17085. this._alphaThreshold = 0.5;
  17086. this._fireColors = FireProceduralTexture.RedFireColors;
  17087. this.updateShaderUniforms();
  17088. this.refreshRate = 1;
  17089. }
  17090. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17091. this.setFloat("time", this._time);
  17092. this.setVector2("speed", this._speed);
  17093. this.setColor3("c1", this._fireColors[0]);
  17094. this.setColor3("c2", this._fireColors[1]);
  17095. this.setColor3("c3", this._fireColors[2]);
  17096. this.setColor3("c4", this._fireColors[3]);
  17097. this.setColor3("c5", this._fireColors[4]);
  17098. this.setColor3("c6", this._fireColors[5]);
  17099. this.setFloat("alphaThreshold", this._alphaThreshold);
  17100. };
  17101. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17102. if (this._autoGenerateTime) {
  17103. this._time += this.getScene().getAnimationRatio() * 0.03;
  17104. this.updateShaderUniforms();
  17105. }
  17106. _super.prototype.render.call(this, useCameraPostProcess);
  17107. };
  17108. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17109. get: function () {
  17110. return [
  17111. new BABYLON.Color3(0.5, 0.0, 1.0),
  17112. new BABYLON.Color3(0.9, 0.0, 1.0),
  17113. new BABYLON.Color3(0.2, 0.0, 1.0),
  17114. new BABYLON.Color3(1.0, 0.9, 1.0),
  17115. new BABYLON.Color3(0.1, 0.1, 1.0),
  17116. new BABYLON.Color3(0.9, 0.9, 1.0)
  17117. ];
  17118. },
  17119. enumerable: true,
  17120. configurable: true
  17121. });
  17122. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17123. get: function () {
  17124. return [
  17125. new BABYLON.Color3(0.5, 1.0, 0.0),
  17126. new BABYLON.Color3(0.5, 1.0, 0.0),
  17127. new BABYLON.Color3(0.3, 0.4, 0.0),
  17128. new BABYLON.Color3(0.5, 1.0, 0.0),
  17129. new BABYLON.Color3(0.2, 0.0, 0.0),
  17130. new BABYLON.Color3(0.5, 1.0, 0.0)
  17131. ];
  17132. },
  17133. enumerable: true,
  17134. configurable: true
  17135. });
  17136. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17137. get: function () {
  17138. return [
  17139. new BABYLON.Color3(0.5, 0.0, 0.1),
  17140. new BABYLON.Color3(0.9, 0.0, 0.0),
  17141. new BABYLON.Color3(0.2, 0.0, 0.0),
  17142. new BABYLON.Color3(1.0, 0.9, 0.0),
  17143. new BABYLON.Color3(0.1, 0.1, 0.1),
  17144. new BABYLON.Color3(0.9, 0.9, 0.9)
  17145. ];
  17146. },
  17147. enumerable: true,
  17148. configurable: true
  17149. });
  17150. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17151. get: function () {
  17152. return [
  17153. new BABYLON.Color3(0.1, 0.0, 0.5),
  17154. new BABYLON.Color3(0.0, 0.0, 0.5),
  17155. new BABYLON.Color3(0.1, 0.0, 0.2),
  17156. new BABYLON.Color3(0.0, 0.0, 1.0),
  17157. new BABYLON.Color3(0.1, 0.2, 0.3),
  17158. new BABYLON.Color3(0.0, 0.2, 0.9)
  17159. ];
  17160. },
  17161. enumerable: true,
  17162. configurable: true
  17163. });
  17164. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17165. get: function () {
  17166. return this._fireColors;
  17167. },
  17168. set: function (value) {
  17169. this._fireColors = value;
  17170. this.updateShaderUniforms();
  17171. },
  17172. enumerable: true,
  17173. configurable: true
  17174. });
  17175. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17176. get: function () {
  17177. return this._time;
  17178. },
  17179. set: function (value) {
  17180. this._time = value;
  17181. this.updateShaderUniforms();
  17182. },
  17183. enumerable: true,
  17184. configurable: true
  17185. });
  17186. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17187. get: function () {
  17188. return this._speed;
  17189. },
  17190. set: function (value) {
  17191. this._speed = value;
  17192. this.updateShaderUniforms();
  17193. },
  17194. enumerable: true,
  17195. configurable: true
  17196. });
  17197. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17198. get: function () {
  17199. return this._alphaThreshold;
  17200. },
  17201. set: function (value) {
  17202. this._alphaThreshold = value;
  17203. this.updateShaderUniforms();
  17204. },
  17205. enumerable: true,
  17206. configurable: true
  17207. });
  17208. return FireProceduralTexture;
  17209. })(BABYLON.ProceduralTexture);
  17210. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17211. var CloudProceduralTexture = (function (_super) {
  17212. __extends(CloudProceduralTexture, _super);
  17213. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17214. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17215. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  17216. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  17217. this.updateShaderUniforms();
  17218. this.refreshRate = 0;
  17219. }
  17220. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17221. this.setColor3("skyColor", this._skyColor);
  17222. this.setColor3("cloudColor", this._cloudColor);
  17223. };
  17224. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17225. get: function () {
  17226. return this._skyColor;
  17227. },
  17228. set: function (value) {
  17229. this._skyColor = value;
  17230. this.updateShaderUniforms();
  17231. },
  17232. enumerable: true,
  17233. configurable: true
  17234. });
  17235. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17236. get: function () {
  17237. return this._cloudColor;
  17238. },
  17239. set: function (value) {
  17240. this._cloudColor = value;
  17241. this.updateShaderUniforms();
  17242. },
  17243. enumerable: true,
  17244. configurable: true
  17245. });
  17246. return CloudProceduralTexture;
  17247. })(BABYLON.ProceduralTexture);
  17248. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17249. var GrassProceduralTexture = (function (_super) {
  17250. __extends(GrassProceduralTexture, _super);
  17251. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17252. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17253. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17254. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17255. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17256. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17257. this._grassColors = [
  17258. new BABYLON.Color3(0.29, 0.38, 0.02),
  17259. new BABYLON.Color3(0.36, 0.49, 0.09),
  17260. new BABYLON.Color3(0.51, 0.6, 0.28)
  17261. ];
  17262. this.updateShaderUniforms();
  17263. this.refreshRate = 0;
  17264. }
  17265. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17266. this.setColor3("herb1Color", this._grassColors[0]);
  17267. this.setColor3("herb2Color", this._grassColors[1]);
  17268. this.setColor3("herb3Color", this._grassColors[2]);
  17269. this.setColor3("groundColor", this._groundColor);
  17270. };
  17271. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17272. get: function () {
  17273. return this._grassColors;
  17274. },
  17275. set: function (value) {
  17276. this._grassColors = value;
  17277. this.updateShaderUniforms();
  17278. },
  17279. enumerable: true,
  17280. configurable: true
  17281. });
  17282. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17283. get: function () {
  17284. return this._groundColor;
  17285. },
  17286. set: function (value) {
  17287. this.groundColor = value;
  17288. this.updateShaderUniforms();
  17289. },
  17290. enumerable: true,
  17291. configurable: true
  17292. });
  17293. return GrassProceduralTexture;
  17294. })(BABYLON.ProceduralTexture);
  17295. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17296. var RoadProceduralTexture = (function (_super) {
  17297. __extends(RoadProceduralTexture, _super);
  17298. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17299. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17300. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17301. this.updateShaderUniforms();
  17302. this.refreshRate = 0;
  17303. }
  17304. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17305. this.setColor3("roadColor", this._roadColor);
  17306. };
  17307. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17308. get: function () {
  17309. return this._roadColor;
  17310. },
  17311. set: function (value) {
  17312. this._roadColor = value;
  17313. this.updateShaderUniforms();
  17314. },
  17315. enumerable: true,
  17316. configurable: true
  17317. });
  17318. return RoadProceduralTexture;
  17319. })(BABYLON.ProceduralTexture);
  17320. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17321. var BrickProceduralTexture = (function (_super) {
  17322. __extends(BrickProceduralTexture, _super);
  17323. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17324. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17325. this._numberOfBricksHeight = 15;
  17326. this._numberOfBricksWidth = 5;
  17327. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17328. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17329. this.updateShaderUniforms();
  17330. this.refreshRate = 0;
  17331. }
  17332. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17333. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17334. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17335. this.setColor3("brickColor", this._brickColor);
  17336. this.setColor3("jointColor", this._jointColor);
  17337. };
  17338. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17339. get: function () {
  17340. return this._numberOfBricksHeight;
  17341. },
  17342. set: function (value) {
  17343. this._numberOfBricksHeight = value;
  17344. this.updateShaderUniforms();
  17345. },
  17346. enumerable: true,
  17347. configurable: true
  17348. });
  17349. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17350. get: function () {
  17351. return this._numberOfBricksWidth;
  17352. },
  17353. set: function (value) {
  17354. this._numberOfBricksHeight = value;
  17355. this.updateShaderUniforms();
  17356. },
  17357. enumerable: true,
  17358. configurable: true
  17359. });
  17360. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17361. get: function () {
  17362. return this._jointColor;
  17363. },
  17364. set: function (value) {
  17365. this._jointColor = value;
  17366. this.updateShaderUniforms();
  17367. },
  17368. enumerable: true,
  17369. configurable: true
  17370. });
  17371. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17372. get: function () {
  17373. return this._brickColor;
  17374. },
  17375. set: function (value) {
  17376. this._brickColor = value;
  17377. this.updateShaderUniforms();
  17378. },
  17379. enumerable: true,
  17380. configurable: true
  17381. });
  17382. return BrickProceduralTexture;
  17383. })(BABYLON.ProceduralTexture);
  17384. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17385. var MarbleProceduralTexture = (function (_super) {
  17386. __extends(MarbleProceduralTexture, _super);
  17387. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17388. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17389. this._numberOfTilesHeight = 3;
  17390. this._numberOfTilesWidth = 3;
  17391. this._amplitude = 9.0;
  17392. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17393. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17394. this.updateShaderUniforms();
  17395. this.refreshRate = 0;
  17396. }
  17397. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17398. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17399. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17400. this.setFloat("amplitude", this._amplitude);
  17401. this.setColor3("marbleColor", this._marbleColor);
  17402. this.setColor3("jointColor", this._jointColor);
  17403. };
  17404. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17405. get: function () {
  17406. return this._numberOfTilesHeight;
  17407. },
  17408. set: function (value) {
  17409. this._numberOfTilesHeight = value;
  17410. this.updateShaderUniforms();
  17411. },
  17412. enumerable: true,
  17413. configurable: true
  17414. });
  17415. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17416. get: function () {
  17417. return this._numberOfTilesWidth;
  17418. },
  17419. set: function (value) {
  17420. this._numberOfTilesWidth = value;
  17421. this.updateShaderUniforms();
  17422. },
  17423. enumerable: true,
  17424. configurable: true
  17425. });
  17426. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17427. get: function () {
  17428. return this._jointColor;
  17429. },
  17430. set: function (value) {
  17431. this._jointColor = value;
  17432. this.updateShaderUniforms();
  17433. },
  17434. enumerable: true,
  17435. configurable: true
  17436. });
  17437. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17438. get: function () {
  17439. return this._marbleColor;
  17440. },
  17441. set: function (value) {
  17442. this._marbleColor = value;
  17443. this.updateShaderUniforms();
  17444. },
  17445. enumerable: true,
  17446. configurable: true
  17447. });
  17448. return MarbleProceduralTexture;
  17449. })(BABYLON.ProceduralTexture);
  17450. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17451. })(BABYLON || (BABYLON = {}));
  17452. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  17453. var BABYLON;
  17454. (function (BABYLON) {
  17455. var EffectFallbacks = (function () {
  17456. function EffectFallbacks() {
  17457. this._defines = {};
  17458. this._currentRank = 32;
  17459. this._maxRank = -1;
  17460. }
  17461. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17462. if (!this._defines[rank]) {
  17463. if (rank < this._currentRank) {
  17464. this._currentRank = rank;
  17465. }
  17466. if (rank > this._maxRank) {
  17467. this._maxRank = rank;
  17468. }
  17469. this._defines[rank] = new Array();
  17470. }
  17471. this._defines[rank].push(define);
  17472. };
  17473. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17474. get: function () {
  17475. return this._currentRank <= this._maxRank;
  17476. },
  17477. enumerable: true,
  17478. configurable: true
  17479. });
  17480. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17481. var currentFallbacks = this._defines[this._currentRank];
  17482. for (var index = 0; index < currentFallbacks.length; index++) {
  17483. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17484. }
  17485. this._currentRank++;
  17486. return currentDefines;
  17487. };
  17488. return EffectFallbacks;
  17489. })();
  17490. BABYLON.EffectFallbacks = EffectFallbacks;
  17491. var Effect = (function () {
  17492. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17493. var _this = this;
  17494. this._isReady = false;
  17495. this._compilationError = "";
  17496. this._valueCache = [];
  17497. this._engine = engine;
  17498. this.name = baseName;
  17499. this.defines = defines;
  17500. this._uniformsNames = uniformsNames.concat(samplers);
  17501. this._samplers = samplers;
  17502. this._attributesNames = attributesNames;
  17503. this.onError = onError;
  17504. this.onCompiled = onCompiled;
  17505. var vertexSource;
  17506. var fragmentSource;
  17507. if (baseName.vertexElement) {
  17508. vertexSource = document.getElementById(baseName.vertexElement);
  17509. if (!vertexSource) {
  17510. vertexSource = baseName.vertexElement;
  17511. }
  17512. }
  17513. else {
  17514. vertexSource = baseName.vertex || baseName;
  17515. }
  17516. if (baseName.fragmentElement) {
  17517. fragmentSource = document.getElementById(baseName.fragmentElement);
  17518. if (!fragmentSource) {
  17519. fragmentSource = baseName.fragmentElement;
  17520. }
  17521. }
  17522. else {
  17523. fragmentSource = baseName.fragment || baseName;
  17524. }
  17525. this._loadVertexShader(vertexSource, function (vertexCode) {
  17526. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17527. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17528. });
  17529. });
  17530. }
  17531. // Properties
  17532. Effect.prototype.isReady = function () {
  17533. return this._isReady;
  17534. };
  17535. Effect.prototype.getProgram = function () {
  17536. return this._program;
  17537. };
  17538. Effect.prototype.getAttributesNames = function () {
  17539. return this._attributesNames;
  17540. };
  17541. Effect.prototype.getAttributeLocation = function (index) {
  17542. return this._attributes[index];
  17543. };
  17544. Effect.prototype.getAttributeLocationByName = function (name) {
  17545. var index = this._attributesNames.indexOf(name);
  17546. return this._attributes[index];
  17547. };
  17548. Effect.prototype.getAttributesCount = function () {
  17549. return this._attributes.length;
  17550. };
  17551. Effect.prototype.getUniformIndex = function (uniformName) {
  17552. return this._uniformsNames.indexOf(uniformName);
  17553. };
  17554. Effect.prototype.getUniform = function (uniformName) {
  17555. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17556. };
  17557. Effect.prototype.getSamplers = function () {
  17558. return this._samplers;
  17559. };
  17560. Effect.prototype.getCompilationError = function () {
  17561. return this._compilationError;
  17562. };
  17563. // Methods
  17564. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17565. // DOM element ?
  17566. if (vertex instanceof HTMLElement) {
  17567. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17568. callback(vertexCode);
  17569. return;
  17570. }
  17571. // Is in local store ?
  17572. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17573. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17574. return;
  17575. }
  17576. var vertexShaderUrl;
  17577. if (vertex[0] === ".") {
  17578. vertexShaderUrl = vertex;
  17579. }
  17580. else {
  17581. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17582. }
  17583. // Vertex shader
  17584. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17585. };
  17586. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17587. // DOM element ?
  17588. if (fragment instanceof HTMLElement) {
  17589. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17590. callback(fragmentCode);
  17591. return;
  17592. }
  17593. // Is in local store ?
  17594. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17595. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17596. return;
  17597. }
  17598. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17599. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17600. return;
  17601. }
  17602. var fragmentShaderUrl;
  17603. if (fragment[0] === ".") {
  17604. fragmentShaderUrl = fragment;
  17605. }
  17606. else {
  17607. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17608. }
  17609. // Fragment shader
  17610. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17611. };
  17612. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17613. try {
  17614. var engine = this._engine;
  17615. if (!engine.getCaps().highPrecisionShaderSupported) {
  17616. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17617. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17618. }
  17619. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17620. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17621. this._attributes = engine.getAttributes(this._program, attributesNames);
  17622. for (var index = 0; index < this._samplers.length; index++) {
  17623. var sampler = this.getUniform(this._samplers[index]);
  17624. if (sampler == null) {
  17625. this._samplers.splice(index, 1);
  17626. index--;
  17627. }
  17628. }
  17629. engine.bindSamplers(this);
  17630. this._isReady = true;
  17631. if (this.onCompiled) {
  17632. this.onCompiled(this);
  17633. }
  17634. }
  17635. catch (e) {
  17636. // Is it a problem with precision?
  17637. if (e.message.indexOf("highp") !== -1) {
  17638. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17639. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17640. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17641. return;
  17642. }
  17643. // Let's go through fallbacks then
  17644. if (fallbacks && fallbacks.isMoreFallbacks) {
  17645. defines = fallbacks.reduce(defines);
  17646. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17647. }
  17648. else {
  17649. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  17650. BABYLON.Tools.Error("Defines: " + defines);
  17651. BABYLON.Tools.Error("Error: " + e.message);
  17652. this._compilationError = e.message;
  17653. if (this.onError) {
  17654. this.onError(this, this._compilationError);
  17655. }
  17656. }
  17657. }
  17658. };
  17659. Effect.prototype._bindTexture = function (channel, texture) {
  17660. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17661. };
  17662. Effect.prototype.setTexture = function (channel, texture) {
  17663. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17664. };
  17665. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17666. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17667. };
  17668. //public _cacheMatrix(uniformName, matrix) {
  17669. // if (!this._valueCache[uniformName]) {
  17670. // this._valueCache[uniformName] = new BABYLON.Matrix();
  17671. // }
  17672. // for (var index = 0; index < 16; index++) {
  17673. // this._valueCache[uniformName].m[index] = matrix.m[index];
  17674. // }
  17675. //};
  17676. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17677. if (!this._valueCache[uniformName]) {
  17678. this._valueCache[uniformName] = [x, y];
  17679. return;
  17680. }
  17681. this._valueCache[uniformName][0] = x;
  17682. this._valueCache[uniformName][1] = y;
  17683. };
  17684. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17685. if (!this._valueCache[uniformName]) {
  17686. this._valueCache[uniformName] = [x, y, z];
  17687. return;
  17688. }
  17689. this._valueCache[uniformName][0] = x;
  17690. this._valueCache[uniformName][1] = y;
  17691. this._valueCache[uniformName][2] = z;
  17692. };
  17693. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17694. if (!this._valueCache[uniformName]) {
  17695. this._valueCache[uniformName] = [x, y, z, w];
  17696. return;
  17697. }
  17698. this._valueCache[uniformName][0] = x;
  17699. this._valueCache[uniformName][1] = y;
  17700. this._valueCache[uniformName][2] = z;
  17701. this._valueCache[uniformName][3] = w;
  17702. };
  17703. Effect.prototype.setArray = function (uniformName, array) {
  17704. this._engine.setArray(this.getUniform(uniformName), array);
  17705. return this;
  17706. };
  17707. Effect.prototype.setArray2 = function (uniformName, array) {
  17708. this._engine.setArray2(this.getUniform(uniformName), array);
  17709. return this;
  17710. };
  17711. Effect.prototype.setArray3 = function (uniformName, array) {
  17712. this._engine.setArray3(this.getUniform(uniformName), array);
  17713. return this;
  17714. };
  17715. Effect.prototype.setArray4 = function (uniformName, array) {
  17716. this._engine.setArray4(this.getUniform(uniformName), array);
  17717. return this;
  17718. };
  17719. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17720. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17721. return this;
  17722. };
  17723. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17724. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17725. // return;
  17726. //this._cacheMatrix(uniformName, matrix);
  17727. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17728. return this;
  17729. };
  17730. Effect.prototype.setFloat = function (uniformName, value) {
  17731. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  17732. return this;
  17733. this._valueCache[uniformName] = value;
  17734. this._engine.setFloat(this.getUniform(uniformName), value);
  17735. return this;
  17736. };
  17737. Effect.prototype.setBool = function (uniformName, bool) {
  17738. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  17739. return this;
  17740. this._valueCache[uniformName] = bool;
  17741. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  17742. return this;
  17743. };
  17744. Effect.prototype.setVector2 = function (uniformName, vector2) {
  17745. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17746. return this;
  17747. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17748. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17749. return this;
  17750. };
  17751. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17752. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17753. return this;
  17754. this._cacheFloat2(uniformName, x, y);
  17755. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17756. return this;
  17757. };
  17758. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17759. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17760. return this;
  17761. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17762. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17763. return this;
  17764. };
  17765. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17766. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17767. return this;
  17768. this._cacheFloat3(uniformName, x, y, z);
  17769. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17770. return this;
  17771. };
  17772. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17773. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17774. return this;
  17775. this._cacheFloat4(uniformName, x, y, z, w);
  17776. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17777. return this;
  17778. };
  17779. Effect.prototype.setColor3 = function (uniformName, color3) {
  17780. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  17781. return this;
  17782. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  17783. this._engine.setColor3(this.getUniform(uniformName), color3);
  17784. return this;
  17785. };
  17786. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  17787. 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)
  17788. return this;
  17789. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  17790. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  17791. return this;
  17792. };
  17793. // Statics
  17794. Effect.ShadersStore = {};
  17795. return Effect;
  17796. })();
  17797. BABYLON.Effect = Effect;
  17798. })(BABYLON || (BABYLON = {}));
  17799. //# sourceMappingURL=babylon.effect.js.map
  17800. var BABYLON;
  17801. (function (BABYLON) {
  17802. var Material = (function () {
  17803. function Material(name, scene, doNotAdd) {
  17804. this.name = name;
  17805. this.checkReadyOnEveryCall = true;
  17806. this.checkReadyOnlyOnce = false;
  17807. this.state = "";
  17808. this.alpha = 1.0;
  17809. this.backFaceCulling = true;
  17810. this._wasPreviouslyReady = false;
  17811. this._fillMode = Material.TriangleFillMode;
  17812. this.pointSize = 1.0;
  17813. this.zOffset = 0;
  17814. this.id = name;
  17815. this._scene = scene;
  17816. if (!doNotAdd) {
  17817. scene.materials.push(this);
  17818. }
  17819. }
  17820. Object.defineProperty(Material, "TriangleFillMode", {
  17821. get: function () {
  17822. return Material._TriangleFillMode;
  17823. },
  17824. enumerable: true,
  17825. configurable: true
  17826. });
  17827. Object.defineProperty(Material, "WireFrameFillMode", {
  17828. get: function () {
  17829. return Material._WireFrameFillMode;
  17830. },
  17831. enumerable: true,
  17832. configurable: true
  17833. });
  17834. Object.defineProperty(Material, "PointFillMode", {
  17835. get: function () {
  17836. return Material._PointFillMode;
  17837. },
  17838. enumerable: true,
  17839. configurable: true
  17840. });
  17841. Object.defineProperty(Material.prototype, "wireframe", {
  17842. get: function () {
  17843. return this._fillMode === Material.WireFrameFillMode;
  17844. },
  17845. set: function (value) {
  17846. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  17847. },
  17848. enumerable: true,
  17849. configurable: true
  17850. });
  17851. Object.defineProperty(Material.prototype, "pointsCloud", {
  17852. get: function () {
  17853. return this._fillMode === Material.PointFillMode;
  17854. },
  17855. set: function (value) {
  17856. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  17857. },
  17858. enumerable: true,
  17859. configurable: true
  17860. });
  17861. Object.defineProperty(Material.prototype, "fillMode", {
  17862. get: function () {
  17863. return this._fillMode;
  17864. },
  17865. set: function (value) {
  17866. this._fillMode = value;
  17867. },
  17868. enumerable: true,
  17869. configurable: true
  17870. });
  17871. Material.prototype.isReady = function (mesh, useInstances) {
  17872. return true;
  17873. };
  17874. Material.prototype.getEffect = function () {
  17875. return this._effect;
  17876. };
  17877. Material.prototype.getScene = function () {
  17878. return this._scene;
  17879. };
  17880. Material.prototype.needAlphaBlending = function () {
  17881. return (this.alpha < 1.0);
  17882. };
  17883. Material.prototype.needAlphaTesting = function () {
  17884. return false;
  17885. };
  17886. Material.prototype.getAlphaTestTexture = function () {
  17887. return null;
  17888. };
  17889. Material.prototype.trackCreation = function (onCompiled, onError) {
  17890. };
  17891. Material.prototype._preBind = function () {
  17892. var engine = this._scene.getEngine();
  17893. engine.enableEffect(this._effect);
  17894. engine.setState(this.backFaceCulling, this.zOffset);
  17895. };
  17896. Material.prototype.bind = function (world, mesh) {
  17897. this._scene._cachedMaterial = this;
  17898. if (this.onBind) {
  17899. this.onBind(this, mesh);
  17900. }
  17901. };
  17902. Material.prototype.bindOnlyWorldMatrix = function (world) {
  17903. };
  17904. Material.prototype.unbind = function () {
  17905. };
  17906. Material.prototype.dispose = function (forceDisposeEffect) {
  17907. // Remove from scene
  17908. var index = this._scene.materials.indexOf(this);
  17909. this._scene.materials.splice(index, 1);
  17910. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  17911. if (forceDisposeEffect && this._effect) {
  17912. this._scene.getEngine()._releaseEffect(this._effect);
  17913. this._effect = null;
  17914. }
  17915. // Callback
  17916. if (this.onDispose) {
  17917. this.onDispose();
  17918. }
  17919. };
  17920. Material._TriangleFillMode = 0;
  17921. Material._WireFrameFillMode = 1;
  17922. Material._PointFillMode = 2;
  17923. return Material;
  17924. })();
  17925. BABYLON.Material = Material;
  17926. })(BABYLON || (BABYLON = {}));
  17927. //# sourceMappingURL=babylon.material.js.map
  17928. var __extends = this.__extends || function (d, b) {
  17929. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17930. function __() { this.constructor = d; }
  17931. __.prototype = b.prototype;
  17932. d.prototype = new __();
  17933. };
  17934. var BABYLON;
  17935. (function (BABYLON) {
  17936. var maxSimultaneousLights = 4;
  17937. var FresnelParameters = (function () {
  17938. function FresnelParameters() {
  17939. this.isEnabled = true;
  17940. this.leftColor = BABYLON.Color3.White();
  17941. this.rightColor = BABYLON.Color3.Black();
  17942. this.bias = 0;
  17943. this.power = 1;
  17944. }
  17945. return FresnelParameters;
  17946. })();
  17947. BABYLON.FresnelParameters = FresnelParameters;
  17948. var StandardMaterial = (function (_super) {
  17949. __extends(StandardMaterial, _super);
  17950. function StandardMaterial(name, scene) {
  17951. var _this = this;
  17952. _super.call(this, name, scene);
  17953. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17954. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  17955. this.specularColor = new BABYLON.Color3(1, 1, 1);
  17956. this.specularPower = 64;
  17957. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  17958. this.useAlphaFromDiffuseTexture = false;
  17959. this.useSpecularOverAlpha = true;
  17960. this.fogEnabled = true;
  17961. this._cachedDefines = null;
  17962. this._renderTargets = new BABYLON.SmartArray(16);
  17963. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  17964. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  17965. this._scaledDiffuse = new BABYLON.Color3();
  17966. this._scaledSpecular = new BABYLON.Color3();
  17967. this.getRenderTargetTextures = function () {
  17968. _this._renderTargets.reset();
  17969. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  17970. _this._renderTargets.push(_this.reflectionTexture);
  17971. }
  17972. return _this._renderTargets;
  17973. };
  17974. }
  17975. StandardMaterial.prototype.needAlphaBlending = function () {
  17976. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  17977. };
  17978. StandardMaterial.prototype.needAlphaTesting = function () {
  17979. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  17980. };
  17981. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  17982. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  17983. };
  17984. StandardMaterial.prototype.getAlphaTestTexture = function () {
  17985. return this.diffuseTexture;
  17986. };
  17987. // Methods
  17988. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  17989. if (this.checkReadyOnlyOnce) {
  17990. if (this._wasPreviouslyReady) {
  17991. return true;
  17992. }
  17993. }
  17994. var scene = this.getScene();
  17995. if (!this.checkReadyOnEveryCall) {
  17996. if (this._renderId === scene.getRenderId()) {
  17997. return true;
  17998. }
  17999. }
  18000. var engine = scene.getEngine();
  18001. var defines = [];
  18002. var fallbacks = new BABYLON.EffectFallbacks();
  18003. var needNormals = false;
  18004. var needUVs = false;
  18005. // Textures
  18006. if (scene.texturesEnabled) {
  18007. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18008. if (!this.diffuseTexture.isReady()) {
  18009. return false;
  18010. }
  18011. else {
  18012. needUVs = true;
  18013. defines.push("#define DIFFUSE");
  18014. }
  18015. }
  18016. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18017. if (!this.ambientTexture.isReady()) {
  18018. return false;
  18019. }
  18020. else {
  18021. needUVs = true;
  18022. defines.push("#define AMBIENT");
  18023. }
  18024. }
  18025. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18026. if (!this.opacityTexture.isReady()) {
  18027. return false;
  18028. }
  18029. else {
  18030. needUVs = true;
  18031. defines.push("#define OPACITY");
  18032. if (this.opacityTexture.getAlphaFromRGB) {
  18033. defines.push("#define OPACITYRGB");
  18034. }
  18035. }
  18036. }
  18037. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18038. if (!this.reflectionTexture.isReady()) {
  18039. return false;
  18040. }
  18041. else {
  18042. needNormals = true;
  18043. needUVs = true;
  18044. defines.push("#define REFLECTION");
  18045. fallbacks.addFallback(0, "REFLECTION");
  18046. }
  18047. }
  18048. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18049. if (!this.emissiveTexture.isReady()) {
  18050. return false;
  18051. }
  18052. else {
  18053. needUVs = true;
  18054. defines.push("#define EMISSIVE");
  18055. }
  18056. }
  18057. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18058. if (!this.specularTexture.isReady()) {
  18059. return false;
  18060. }
  18061. else {
  18062. needUVs = true;
  18063. defines.push("#define SPECULAR");
  18064. fallbacks.addFallback(0, "SPECULAR");
  18065. }
  18066. }
  18067. }
  18068. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18069. if (!this.bumpTexture.isReady()) {
  18070. return false;
  18071. }
  18072. else {
  18073. needUVs = true;
  18074. defines.push("#define BUMP");
  18075. fallbacks.addFallback(0, "BUMP");
  18076. }
  18077. }
  18078. // Effect
  18079. if (this.useSpecularOverAlpha) {
  18080. defines.push("#define SPECULAROVERALPHA");
  18081. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18082. }
  18083. if (scene.clipPlane) {
  18084. defines.push("#define CLIPPLANE");
  18085. }
  18086. if (engine.getAlphaTesting()) {
  18087. defines.push("#define ALPHATEST");
  18088. }
  18089. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18090. defines.push("#define ALPHAFROMDIFFUSE");
  18091. }
  18092. // Point size
  18093. if (this.pointsCloud || scene.forcePointsCloud) {
  18094. defines.push("#define POINTSIZE");
  18095. }
  18096. // Fog
  18097. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18098. defines.push("#define FOG");
  18099. fallbacks.addFallback(1, "FOG");
  18100. }
  18101. var shadowsActivated = false;
  18102. var lightIndex = 0;
  18103. if (scene.lightsEnabled) {
  18104. for (var index = 0; index < scene.lights.length; index++) {
  18105. var light = scene.lights[index];
  18106. if (!light.isEnabled()) {
  18107. continue;
  18108. }
  18109. // Excluded check
  18110. if (light._excludedMeshesIds.length > 0) {
  18111. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18112. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18113. if (excludedMesh) {
  18114. light.excludedMeshes.push(excludedMesh);
  18115. }
  18116. }
  18117. light._excludedMeshesIds = [];
  18118. }
  18119. // Included check
  18120. if (light._includedOnlyMeshesIds.length > 0) {
  18121. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18122. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18123. if (includedOnlyMesh) {
  18124. light.includedOnlyMeshes.push(includedOnlyMesh);
  18125. }
  18126. }
  18127. light._includedOnlyMeshesIds = [];
  18128. }
  18129. if (!light.canAffectMesh(mesh)) {
  18130. continue;
  18131. }
  18132. needNormals = true;
  18133. defines.push("#define LIGHT" + lightIndex);
  18134. if (lightIndex > 0) {
  18135. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18136. }
  18137. var type;
  18138. if (light instanceof BABYLON.SpotLight) {
  18139. type = "#define SPOTLIGHT" + lightIndex;
  18140. }
  18141. else if (light instanceof BABYLON.HemisphericLight) {
  18142. type = "#define HEMILIGHT" + lightIndex;
  18143. }
  18144. else {
  18145. type = "#define POINTDIRLIGHT" + lightIndex;
  18146. }
  18147. defines.push(type);
  18148. if (lightIndex > 0) {
  18149. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  18150. }
  18151. // Shadows
  18152. if (scene.shadowsEnabled) {
  18153. var shadowGenerator = light.getShadowGenerator();
  18154. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18155. defines.push("#define SHADOW" + lightIndex);
  18156. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18157. if (!shadowsActivated) {
  18158. defines.push("#define SHADOWS");
  18159. shadowsActivated = true;
  18160. }
  18161. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18162. defines.push("#define SHADOWVSM" + lightIndex);
  18163. if (lightIndex > 0) {
  18164. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18165. }
  18166. }
  18167. if (shadowGenerator.usePoissonSampling) {
  18168. defines.push("#define SHADOWPCF" + lightIndex);
  18169. if (lightIndex > 0) {
  18170. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18171. }
  18172. }
  18173. }
  18174. }
  18175. lightIndex++;
  18176. if (lightIndex === maxSimultaneousLights)
  18177. break;
  18178. }
  18179. }
  18180. if (StandardMaterial.FresnelEnabled) {
  18181. // Fresnel
  18182. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18183. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18184. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18185. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18186. var fresnelRank = 1;
  18187. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18188. defines.push("#define DIFFUSEFRESNEL");
  18189. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  18190. fresnelRank++;
  18191. }
  18192. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18193. defines.push("#define OPACITYFRESNEL");
  18194. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  18195. fresnelRank++;
  18196. }
  18197. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18198. defines.push("#define REFLECTIONFRESNEL");
  18199. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  18200. fresnelRank++;
  18201. }
  18202. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18203. defines.push("#define EMISSIVEFRESNEL");
  18204. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  18205. fresnelRank++;
  18206. }
  18207. needNormals = true;
  18208. defines.push("#define FRESNEL");
  18209. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  18210. }
  18211. }
  18212. // Attribs
  18213. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18214. if (mesh) {
  18215. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18216. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18217. defines.push("#define NORMAL");
  18218. }
  18219. if (needUVs) {
  18220. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18221. attribs.push(BABYLON.VertexBuffer.UVKind);
  18222. defines.push("#define UV1");
  18223. }
  18224. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18225. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18226. defines.push("#define UV2");
  18227. }
  18228. }
  18229. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18230. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18231. defines.push("#define VERTEXCOLOR");
  18232. if (mesh.hasVertexAlpha) {
  18233. defines.push("#define VERTEXALPHA");
  18234. }
  18235. }
  18236. if (mesh.useBones) {
  18237. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18238. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18239. defines.push("#define BONES");
  18240. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  18241. defines.push("#define BONES4");
  18242. fallbacks.addFallback(0, "BONES4");
  18243. }
  18244. // Instances
  18245. if (useInstances) {
  18246. defines.push("#define INSTANCES");
  18247. attribs.push("world0");
  18248. attribs.push("world1");
  18249. attribs.push("world2");
  18250. attribs.push("world3");
  18251. }
  18252. }
  18253. // Get correct effect
  18254. var join = defines.join("\n");
  18255. if (this._cachedDefines !== join) {
  18256. this._cachedDefines = join;
  18257. scene.resetCachedMaterial();
  18258. // Legacy browser patch
  18259. var shaderName = "default";
  18260. if (!scene.getEngine().getCaps().standardDerivatives) {
  18261. shaderName = "legacydefault";
  18262. }
  18263. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18264. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18265. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18266. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18267. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18268. "vFogInfos", "vFogColor", "pointSize",
  18269. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  18270. "mBones",
  18271. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  18272. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18273. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18274. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  18275. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18276. ], join, fallbacks, this.onCompiled, this.onError);
  18277. }
  18278. if (!this._effect.isReady()) {
  18279. return false;
  18280. }
  18281. this._renderId = scene.getRenderId();
  18282. this._wasPreviouslyReady = true;
  18283. return true;
  18284. };
  18285. StandardMaterial.prototype.unbind = function () {
  18286. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18287. this._effect.setTexture("reflection2DSampler", null);
  18288. }
  18289. };
  18290. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18291. this._effect.setMatrix("world", world);
  18292. };
  18293. StandardMaterial.prototype.bind = function (world, mesh) {
  18294. var scene = this.getScene();
  18295. // Matrices
  18296. this.bindOnlyWorldMatrix(world);
  18297. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18298. // Bones
  18299. if (mesh && mesh.useBones) {
  18300. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18301. }
  18302. if (scene.getCachedMaterial() !== this) {
  18303. if (StandardMaterial.FresnelEnabled) {
  18304. // Fresnel
  18305. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18306. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18307. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18308. }
  18309. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18310. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18311. }
  18312. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18313. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18314. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18315. }
  18316. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18317. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18318. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18319. }
  18320. }
  18321. // Textures
  18322. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18323. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18324. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18325. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18326. }
  18327. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18328. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18329. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18330. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18331. }
  18332. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18333. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18334. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18335. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18336. }
  18337. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18338. if (this.reflectionTexture.isCube) {
  18339. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18340. }
  18341. else {
  18342. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18343. }
  18344. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18345. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  18346. }
  18347. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18348. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18349. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18350. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18351. }
  18352. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18353. this._effect.setTexture("specularSampler", this.specularTexture);
  18354. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18355. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18356. }
  18357. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18358. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18359. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18360. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18361. }
  18362. // Clip plane
  18363. if (scene.clipPlane) {
  18364. var clipPlane = scene.clipPlane;
  18365. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18366. }
  18367. // Point size
  18368. if (this.pointsCloud) {
  18369. this._effect.setFloat("pointSize", this.pointSize);
  18370. }
  18371. // Colors
  18372. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18373. // Scaling down color according to emissive
  18374. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18375. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18376. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18377. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  18378. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18379. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  18380. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18381. }
  18382. // Scaling down color according to emissive
  18383. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18384. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18385. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18386. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  18387. if (scene.lightsEnabled) {
  18388. var lightIndex = 0;
  18389. for (var index = 0; index < scene.lights.length; index++) {
  18390. var light = scene.lights[index];
  18391. if (!light.isEnabled()) {
  18392. continue;
  18393. }
  18394. if (!light.canAffectMesh(mesh)) {
  18395. continue;
  18396. }
  18397. if (light instanceof BABYLON.PointLight) {
  18398. // Point Light
  18399. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18400. }
  18401. else if (light instanceof BABYLON.DirectionalLight) {
  18402. // Directional Light
  18403. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18404. }
  18405. else if (light instanceof BABYLON.SpotLight) {
  18406. // Spot Light
  18407. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18408. }
  18409. else if (light instanceof BABYLON.HemisphericLight) {
  18410. // Hemispheric Light
  18411. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18412. }
  18413. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  18414. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  18415. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  18416. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  18417. // Shadows
  18418. if (scene.shadowsEnabled) {
  18419. var shadowGenerator = light.getShadowGenerator();
  18420. if (mesh.receiveShadows && shadowGenerator) {
  18421. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18422. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18423. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18424. }
  18425. }
  18426. lightIndex++;
  18427. if (lightIndex === maxSimultaneousLights)
  18428. break;
  18429. }
  18430. }
  18431. // View
  18432. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  18433. this._effect.setMatrix("view", scene.getViewMatrix());
  18434. }
  18435. // Fog
  18436. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  18437. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  18438. this._effect.setColor3("vFogColor", scene.fogColor);
  18439. }
  18440. _super.prototype.bind.call(this, world, mesh);
  18441. };
  18442. StandardMaterial.prototype.getAnimatables = function () {
  18443. var results = [];
  18444. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  18445. results.push(this.diffuseTexture);
  18446. }
  18447. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  18448. results.push(this.ambientTexture);
  18449. }
  18450. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  18451. results.push(this.opacityTexture);
  18452. }
  18453. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  18454. results.push(this.reflectionTexture);
  18455. }
  18456. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  18457. results.push(this.emissiveTexture);
  18458. }
  18459. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  18460. results.push(this.specularTexture);
  18461. }
  18462. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  18463. results.push(this.bumpTexture);
  18464. }
  18465. return results;
  18466. };
  18467. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  18468. if (this.diffuseTexture) {
  18469. this.diffuseTexture.dispose();
  18470. }
  18471. if (this.ambientTexture) {
  18472. this.ambientTexture.dispose();
  18473. }
  18474. if (this.opacityTexture) {
  18475. this.opacityTexture.dispose();
  18476. }
  18477. if (this.reflectionTexture) {
  18478. this.reflectionTexture.dispose();
  18479. }
  18480. if (this.emissiveTexture) {
  18481. this.emissiveTexture.dispose();
  18482. }
  18483. if (this.specularTexture) {
  18484. this.specularTexture.dispose();
  18485. }
  18486. if (this.bumpTexture) {
  18487. this.bumpTexture.dispose();
  18488. }
  18489. _super.prototype.dispose.call(this, forceDisposeEffect);
  18490. };
  18491. StandardMaterial.prototype.clone = function (name) {
  18492. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  18493. // Base material
  18494. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18495. newStandardMaterial.alpha = this.alpha;
  18496. newStandardMaterial.fillMode = this.fillMode;
  18497. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  18498. // Standard material
  18499. if (this.diffuseTexture && this.diffuseTexture.clone) {
  18500. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  18501. }
  18502. if (this.ambientTexture && this.ambientTexture.clone) {
  18503. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  18504. }
  18505. if (this.opacityTexture && this.opacityTexture.clone) {
  18506. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  18507. }
  18508. if (this.reflectionTexture && this.reflectionTexture.clone) {
  18509. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  18510. }
  18511. if (this.emissiveTexture && this.emissiveTexture.clone) {
  18512. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  18513. }
  18514. if (this.specularTexture && this.specularTexture.clone) {
  18515. newStandardMaterial.specularTexture = this.specularTexture.clone();
  18516. }
  18517. if (this.bumpTexture && this.bumpTexture.clone) {
  18518. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  18519. }
  18520. newStandardMaterial.ambientColor = this.ambientColor.clone();
  18521. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  18522. newStandardMaterial.specularColor = this.specularColor.clone();
  18523. newStandardMaterial.specularPower = this.specularPower;
  18524. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  18525. return newStandardMaterial;
  18526. };
  18527. // Statics
  18528. // Flags used to enable or disable a type of texture for all Standard Materials
  18529. StandardMaterial.DiffuseTextureEnabled = true;
  18530. StandardMaterial.AmbientTextureEnabled = true;
  18531. StandardMaterial.OpacityTextureEnabled = true;
  18532. StandardMaterial.ReflectionTextureEnabled = true;
  18533. StandardMaterial.EmissiveTextureEnabled = true;
  18534. StandardMaterial.SpecularTextureEnabled = true;
  18535. StandardMaterial.BumpTextureEnabled = true;
  18536. StandardMaterial.FresnelEnabled = true;
  18537. return StandardMaterial;
  18538. })(BABYLON.Material);
  18539. BABYLON.StandardMaterial = StandardMaterial;
  18540. })(BABYLON || (BABYLON = {}));
  18541. //# sourceMappingURL=babylon.standardMaterial.js.map
  18542. var __extends = this.__extends || function (d, b) {
  18543. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18544. function __() { this.constructor = d; }
  18545. __.prototype = b.prototype;
  18546. d.prototype = new __();
  18547. };
  18548. var BABYLON;
  18549. (function (BABYLON) {
  18550. var MultiMaterial = (function (_super) {
  18551. __extends(MultiMaterial, _super);
  18552. function MultiMaterial(name, scene) {
  18553. _super.call(this, name, scene, true);
  18554. this.subMaterials = new Array();
  18555. scene.multiMaterials.push(this);
  18556. }
  18557. // Properties
  18558. MultiMaterial.prototype.getSubMaterial = function (index) {
  18559. if (index < 0 || index >= this.subMaterials.length) {
  18560. return this.getScene().defaultMaterial;
  18561. }
  18562. return this.subMaterials[index];
  18563. };
  18564. // Methods
  18565. MultiMaterial.prototype.isReady = function (mesh) {
  18566. for (var index = 0; index < this.subMaterials.length; index++) {
  18567. var subMaterial = this.subMaterials[index];
  18568. if (subMaterial) {
  18569. if (!this.subMaterials[index].isReady(mesh)) {
  18570. return false;
  18571. }
  18572. }
  18573. }
  18574. return true;
  18575. };
  18576. MultiMaterial.prototype.clone = function (name) {
  18577. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  18578. for (var index = 0; index < this.subMaterials.length; index++) {
  18579. var subMaterial = this.subMaterials[index];
  18580. newMultiMaterial.subMaterials.push(subMaterial);
  18581. }
  18582. return newMultiMaterial;
  18583. };
  18584. return MultiMaterial;
  18585. })(BABYLON.Material);
  18586. BABYLON.MultiMaterial = MultiMaterial;
  18587. })(BABYLON || (BABYLON = {}));
  18588. //# sourceMappingURL=babylon.multiMaterial.js.map
  18589. var BABYLON;
  18590. (function (BABYLON) {
  18591. var SceneLoader = (function () {
  18592. function SceneLoader() {
  18593. }
  18594. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18595. get: function () {
  18596. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18597. },
  18598. set: function (value) {
  18599. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18600. },
  18601. enumerable: true,
  18602. configurable: true
  18603. });
  18604. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18605. get: function () {
  18606. return SceneLoader._ShowLoadingScreen;
  18607. },
  18608. set: function (value) {
  18609. SceneLoader._ShowLoadingScreen = value;
  18610. },
  18611. enumerable: true,
  18612. configurable: true
  18613. });
  18614. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18615. var dotPosition = sceneFilename.lastIndexOf(".");
  18616. var queryStringPosition = sceneFilename.indexOf("?");
  18617. if (queryStringPosition === -1) {
  18618. queryStringPosition = sceneFilename.length;
  18619. }
  18620. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18621. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18622. var plugin = this._registeredPlugins[index];
  18623. if (plugin.extensions.indexOf(extension) !== -1) {
  18624. return plugin;
  18625. }
  18626. }
  18627. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18628. };
  18629. // Public functions
  18630. SceneLoader.RegisterPlugin = function (plugin) {
  18631. plugin.extensions = plugin.extensions.toLowerCase();
  18632. SceneLoader._registeredPlugins.push(plugin);
  18633. };
  18634. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18635. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18636. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18637. return;
  18638. }
  18639. var manifestChecked = function (success) {
  18640. scene.database = database;
  18641. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18642. var importMeshFromData = function (data) {
  18643. var meshes = [];
  18644. var particleSystems = [];
  18645. var skeletons = [];
  18646. try {
  18647. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18648. if (onerror) {
  18649. onerror(scene, 'unable to load the scene');
  18650. }
  18651. return;
  18652. }
  18653. }
  18654. catch (e) {
  18655. if (onerror) {
  18656. onerror(scene, e);
  18657. }
  18658. return;
  18659. }
  18660. if (onsuccess) {
  18661. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18662. onsuccess(meshes, particleSystems, skeletons);
  18663. }
  18664. };
  18665. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18666. // Direct load
  18667. importMeshFromData(sceneFilename.substr(5));
  18668. return;
  18669. }
  18670. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18671. importMeshFromData(data);
  18672. }, progressCallBack, database);
  18673. };
  18674. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18675. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18676. };
  18677. /**
  18678. * Load a scene
  18679. * @param rootUrl a string that defines the root url for scene and resources
  18680. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18681. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18682. */
  18683. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18684. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18685. };
  18686. /**
  18687. * Append a scene
  18688. * @param rootUrl a string that defines the root url for scene and resources
  18689. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18690. * @param scene is the instance of BABYLON.Scene to append to
  18691. */
  18692. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18693. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18694. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18695. return;
  18696. }
  18697. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18698. var database;
  18699. if (SceneLoader.ShowLoadingScreen) {
  18700. scene.getEngine().displayLoadingUI();
  18701. }
  18702. var loadSceneFromData = function (data) {
  18703. scene.database = database;
  18704. if (!plugin.load(scene, data, rootUrl)) {
  18705. if (onerror) {
  18706. onerror(scene);
  18707. }
  18708. scene.getEngine().hideLoadingUI();
  18709. return;
  18710. }
  18711. if (onsuccess) {
  18712. onsuccess(scene);
  18713. }
  18714. if (SceneLoader.ShowLoadingScreen) {
  18715. scene.executeWhenReady(function () {
  18716. scene.getEngine().hideLoadingUI();
  18717. });
  18718. }
  18719. };
  18720. var manifestChecked = function (success) {
  18721. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18722. };
  18723. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18724. // Direct load
  18725. loadSceneFromData(sceneFilename.substr(5));
  18726. return;
  18727. }
  18728. if (rootUrl.indexOf("file:") === -1) {
  18729. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18730. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18731. }
  18732. else {
  18733. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18734. }
  18735. };
  18736. // Flags
  18737. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18738. SceneLoader._ShowLoadingScreen = true;
  18739. // Members
  18740. SceneLoader._registeredPlugins = new Array();
  18741. return SceneLoader;
  18742. })();
  18743. BABYLON.SceneLoader = SceneLoader;
  18744. ;
  18745. })(BABYLON || (BABYLON = {}));
  18746. //# sourceMappingURL=babylon.sceneLoader.js.map
  18747. var BABYLON;
  18748. (function (BABYLON) {
  18749. var Internals;
  18750. (function (Internals) {
  18751. var checkColors4 = function (colors, count) {
  18752. // Check if color3 was used
  18753. if (colors.length === count * 3) {
  18754. var colors4 = [];
  18755. for (var index = 0; index < colors.length; index += 3) {
  18756. var newIndex = (index / 3) * 4;
  18757. colors4[newIndex] = colors[index];
  18758. colors4[newIndex + 1] = colors[index + 1];
  18759. colors4[newIndex + 2] = colors[index + 2];
  18760. colors4[newIndex + 3] = 1.0;
  18761. }
  18762. return colors4;
  18763. }
  18764. return colors;
  18765. };
  18766. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18767. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18768. texture.name = parsedTexture.name;
  18769. texture.hasAlpha = parsedTexture.hasAlpha;
  18770. texture.level = parsedTexture.level;
  18771. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18772. return texture;
  18773. };
  18774. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18775. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18776. return null;
  18777. }
  18778. if (parsedTexture.isCube) {
  18779. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18780. }
  18781. var texture;
  18782. if (parsedTexture.mirrorPlane) {
  18783. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18784. texture._waitingRenderList = parsedTexture.renderList;
  18785. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18786. }
  18787. else if (parsedTexture.isRenderTarget) {
  18788. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18789. texture._waitingRenderList = parsedTexture.renderList;
  18790. }
  18791. else {
  18792. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18793. }
  18794. texture.name = parsedTexture.name;
  18795. texture.hasAlpha = parsedTexture.hasAlpha;
  18796. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18797. texture.level = parsedTexture.level;
  18798. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18799. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18800. texture.uOffset = parsedTexture.uOffset;
  18801. texture.vOffset = parsedTexture.vOffset;
  18802. texture.uScale = parsedTexture.uScale;
  18803. texture.vScale = parsedTexture.vScale;
  18804. texture.uAng = parsedTexture.uAng;
  18805. texture.vAng = parsedTexture.vAng;
  18806. texture.wAng = parsedTexture.wAng;
  18807. texture.wrapU = parsedTexture.wrapU;
  18808. texture.wrapV = parsedTexture.wrapV;
  18809. // Animations
  18810. if (parsedTexture.animations) {
  18811. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18812. var parsedAnimation = parsedTexture.animations[animationIndex];
  18813. texture.animations.push(parseAnimation(parsedAnimation));
  18814. }
  18815. }
  18816. return texture;
  18817. };
  18818. var parseSkeleton = function (parsedSkeleton, scene) {
  18819. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18820. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18821. var parsedBone = parsedSkeleton.bones[index];
  18822. var parentBone = null;
  18823. if (parsedBone.parentBoneIndex > -1) {
  18824. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18825. }
  18826. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18827. if (parsedBone.animation) {
  18828. bone.animations.push(parseAnimation(parsedBone.animation));
  18829. }
  18830. }
  18831. return skeleton;
  18832. };
  18833. var parseFresnelParameters = function (parsedFresnelParameters) {
  18834. var fresnelParameters = new BABYLON.FresnelParameters();
  18835. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18836. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18837. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18838. fresnelParameters.bias = parsedFresnelParameters.bias;
  18839. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18840. return fresnelParameters;
  18841. };
  18842. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18843. var material;
  18844. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18845. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18846. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18847. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18848. material.specularPower = parsedMaterial.specularPower;
  18849. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18850. material.alpha = parsedMaterial.alpha;
  18851. material.id = parsedMaterial.id;
  18852. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18853. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18854. material.wireframe = parsedMaterial.wireframe;
  18855. if (parsedMaterial.diffuseTexture) {
  18856. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18857. }
  18858. if (parsedMaterial.diffuseFresnelParameters) {
  18859. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18860. }
  18861. if (parsedMaterial.ambientTexture) {
  18862. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18863. }
  18864. if (parsedMaterial.opacityTexture) {
  18865. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18866. }
  18867. if (parsedMaterial.opacityFresnelParameters) {
  18868. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18869. }
  18870. if (parsedMaterial.reflectionTexture) {
  18871. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18872. }
  18873. if (parsedMaterial.reflectionFresnelParameters) {
  18874. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18875. }
  18876. if (parsedMaterial.emissiveTexture) {
  18877. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18878. }
  18879. if (parsedMaterial.emissiveFresnelParameters) {
  18880. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18881. }
  18882. if (parsedMaterial.specularTexture) {
  18883. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18884. }
  18885. if (parsedMaterial.bumpTexture) {
  18886. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18887. }
  18888. return material;
  18889. };
  18890. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18891. for (var index = 0; index < parsedData.materials.length; index++) {
  18892. var parsedMaterial = parsedData.materials[index];
  18893. if (parsedMaterial.id === id) {
  18894. return parseMaterial(parsedMaterial, scene, rootUrl);
  18895. }
  18896. }
  18897. return null;
  18898. };
  18899. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18900. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18901. multiMaterial.id = parsedMultiMaterial.id;
  18902. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18903. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18904. var subMatId = parsedMultiMaterial.materials[matIndex];
  18905. if (subMatId) {
  18906. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18907. }
  18908. else {
  18909. multiMaterial.subMaterials.push(null);
  18910. }
  18911. }
  18912. return multiMaterial;
  18913. };
  18914. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18915. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18916. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18917. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18918. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18919. var parsedFlare = parsedLensFlareSystem.flares[index];
  18920. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18921. }
  18922. return lensFlareSystem;
  18923. };
  18924. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18925. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18926. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18927. if (parsedParticleSystem.textureName) {
  18928. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18929. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18930. }
  18931. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18932. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18933. particleSystem.minSize = parsedParticleSystem.minSize;
  18934. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18935. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18936. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18937. particleSystem.emitter = emitter;
  18938. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18939. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18940. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18941. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18942. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18943. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18944. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18945. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18946. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18947. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18948. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18949. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18950. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18951. particleSystem.start();
  18952. return particleSystem;
  18953. };
  18954. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18955. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18956. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18957. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18958. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18959. shadowGenerator.getShadowMap().renderList.push(mesh);
  18960. }
  18961. if (parsedShadowGenerator.usePoissonSampling) {
  18962. shadowGenerator.usePoissonSampling = true;
  18963. }
  18964. else if (parsedShadowGenerator.useVarianceShadowMap) {
  18965. shadowGenerator.useVarianceShadowMap = true;
  18966. }
  18967. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  18968. shadowGenerator.useBlurVarianceShadowMap = true;
  18969. if (parsedShadowGenerator.blurScale) {
  18970. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  18971. }
  18972. if (parsedShadowGenerator.blurBoxOffset) {
  18973. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  18974. }
  18975. }
  18976. if (parsedShadowGenerator.bias !== undefined) {
  18977. shadowGenerator.bias = parsedShadowGenerator.bias;
  18978. }
  18979. return shadowGenerator;
  18980. };
  18981. var parseAnimation = function (parsedAnimation) {
  18982. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18983. var dataType = parsedAnimation.dataType;
  18984. var keys = [];
  18985. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18986. var key = parsedAnimation.keys[index];
  18987. var data;
  18988. switch (dataType) {
  18989. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18990. data = key.values[0];
  18991. break;
  18992. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18993. data = BABYLON.Quaternion.FromArray(key.values);
  18994. break;
  18995. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18996. data = BABYLON.Matrix.FromArray(key.values);
  18997. break;
  18998. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18999. default:
  19000. data = BABYLON.Vector3.FromArray(key.values);
  19001. break;
  19002. }
  19003. keys.push({
  19004. frame: key.frame,
  19005. value: data
  19006. });
  19007. }
  19008. animation.setKeys(keys);
  19009. return animation;
  19010. };
  19011. var parseLight = function (parsedLight, scene) {
  19012. var light;
  19013. switch (parsedLight.type) {
  19014. case 0:
  19015. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19016. break;
  19017. case 1:
  19018. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19019. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19020. break;
  19021. case 2:
  19022. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19023. break;
  19024. case 3:
  19025. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19026. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19027. break;
  19028. }
  19029. light.id = parsedLight.id;
  19030. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19031. if (parsedLight.intensity !== undefined) {
  19032. light.intensity = parsedLight.intensity;
  19033. }
  19034. if (parsedLight.range) {
  19035. light.range = parsedLight.range;
  19036. }
  19037. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19038. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19039. if (parsedLight.excludedMeshesIds) {
  19040. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19041. }
  19042. // Parent
  19043. if (parsedLight.parentId) {
  19044. light._waitingParentId = parsedLight.parentId;
  19045. }
  19046. if (parsedLight.includedOnlyMeshesIds) {
  19047. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19048. }
  19049. // Animations
  19050. if (parsedLight.animations) {
  19051. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19052. var parsedAnimation = parsedLight.animations[animationIndex];
  19053. light.animations.push(parseAnimation(parsedAnimation));
  19054. }
  19055. }
  19056. if (parsedLight.autoAnimate) {
  19057. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19058. }
  19059. };
  19060. var parseCamera = function (parsedCamera, scene) {
  19061. var camera;
  19062. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19063. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19064. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19065. var alpha = parsedCamera.alpha;
  19066. var beta = parsedCamera.beta;
  19067. var radius = parsedCamera.radius;
  19068. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19069. var eye_space = parsedCamera.eye_space;
  19070. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19071. }
  19072. else {
  19073. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19074. }
  19075. }
  19076. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19077. eye_space = parsedCamera.eye_space;
  19078. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19079. }
  19080. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19081. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19082. }
  19083. else if (parsedCamera.type === "FollowCamera") {
  19084. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19085. camera.heightOffset = parsedCamera.heightOffset;
  19086. camera.radius = parsedCamera.radius;
  19087. camera.rotationOffset = parsedCamera.rotationOffset;
  19088. if (lockedTargetMesh)
  19089. camera.target = lockedTargetMesh;
  19090. }
  19091. else if (parsedCamera.type === "GamepadCamera") {
  19092. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19093. }
  19094. else if (parsedCamera.type === "TouchCamera") {
  19095. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19096. }
  19097. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19098. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19099. }
  19100. else if (parsedCamera.type === "WebVRFreeCamera") {
  19101. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19102. }
  19103. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19104. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19105. }
  19106. else {
  19107. // Free Camera is the default value
  19108. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19109. }
  19110. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19111. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19112. camera.lockedTarget = lockedTargetMesh;
  19113. }
  19114. camera.id = parsedCamera.id;
  19115. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19116. // Parent
  19117. if (parsedCamera.parentId) {
  19118. camera._waitingParentId = parsedCamera.parentId;
  19119. }
  19120. // Target
  19121. if (parsedCamera.target) {
  19122. if (camera.setTarget) {
  19123. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19124. }
  19125. else {
  19126. //For ArcRotate
  19127. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19128. }
  19129. }
  19130. else {
  19131. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19132. }
  19133. camera.fov = parsedCamera.fov;
  19134. camera.minZ = parsedCamera.minZ;
  19135. camera.maxZ = parsedCamera.maxZ;
  19136. camera.speed = parsedCamera.speed;
  19137. camera.inertia = parsedCamera.inertia;
  19138. camera.checkCollisions = parsedCamera.checkCollisions;
  19139. camera.applyGravity = parsedCamera.applyGravity;
  19140. if (parsedCamera.ellipsoid) {
  19141. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19142. }
  19143. // Animations
  19144. if (parsedCamera.animations) {
  19145. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19146. var parsedAnimation = parsedCamera.animations[animationIndex];
  19147. camera.animations.push(parseAnimation(parsedAnimation));
  19148. }
  19149. }
  19150. if (parsedCamera.autoAnimate) {
  19151. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19152. }
  19153. // Layer Mask
  19154. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19155. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19156. }
  19157. else {
  19158. camera.layerMask = 0xFFFFFFFF;
  19159. }
  19160. return camera;
  19161. };
  19162. var parseGeometry = function (parsedGeometry, scene) {
  19163. var id = parsedGeometry.id;
  19164. return scene.getGeometryByID(id);
  19165. };
  19166. var parseBox = function (parsedBox, scene) {
  19167. if (parseGeometry(parsedBox, scene)) {
  19168. return null; // null since geometry could be something else than a box...
  19169. }
  19170. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19171. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19172. scene.pushGeometry(box, true);
  19173. return box;
  19174. };
  19175. var parseSphere = function (parsedSphere, scene) {
  19176. if (parseGeometry(parsedSphere, scene)) {
  19177. return null; // null since geometry could be something else than a sphere...
  19178. }
  19179. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19180. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19181. scene.pushGeometry(sphere, true);
  19182. return sphere;
  19183. };
  19184. var parseCylinder = function (parsedCylinder, scene) {
  19185. if (parseGeometry(parsedCylinder, scene)) {
  19186. return null; // null since geometry could be something else than a cylinder...
  19187. }
  19188. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19189. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19190. scene.pushGeometry(cylinder, true);
  19191. return cylinder;
  19192. };
  19193. var parseTorus = function (parsedTorus, scene) {
  19194. if (parseGeometry(parsedTorus, scene)) {
  19195. return null; // null since geometry could be something else than a torus...
  19196. }
  19197. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19198. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19199. scene.pushGeometry(torus, true);
  19200. return torus;
  19201. };
  19202. var parseGround = function (parsedGround, scene) {
  19203. if (parseGeometry(parsedGround, scene)) {
  19204. return null; // null since geometry could be something else than a ground...
  19205. }
  19206. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19207. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19208. scene.pushGeometry(ground, true);
  19209. return ground;
  19210. };
  19211. var parsePlane = function (parsedPlane, scene) {
  19212. if (parseGeometry(parsedPlane, scene)) {
  19213. return null; // null since geometry could be something else than a plane...
  19214. }
  19215. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19216. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19217. scene.pushGeometry(plane, true);
  19218. return plane;
  19219. };
  19220. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19221. if (parseGeometry(parsedTorusKnot, scene)) {
  19222. return null; // null since geometry could be something else than a torusKnot...
  19223. }
  19224. 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);
  19225. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19226. scene.pushGeometry(torusKnot, true);
  19227. return torusKnot;
  19228. };
  19229. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19230. if (parseGeometry(parsedVertexData, scene)) {
  19231. return null; // null since geometry could be a primitive
  19232. }
  19233. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19234. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19235. if (parsedVertexData.delayLoadingFile) {
  19236. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19237. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19238. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19239. geometry._delayInfo = [];
  19240. if (parsedVertexData.hasUVs) {
  19241. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19242. }
  19243. if (parsedVertexData.hasUVs2) {
  19244. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19245. }
  19246. if (parsedVertexData.hasColors) {
  19247. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19248. }
  19249. if (parsedVertexData.hasMatricesIndices) {
  19250. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19251. }
  19252. if (parsedVertexData.hasMatricesWeights) {
  19253. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19254. }
  19255. geometry._delayLoadingFunction = importVertexData;
  19256. }
  19257. else {
  19258. importVertexData(parsedVertexData, geometry);
  19259. }
  19260. scene.pushGeometry(geometry, true);
  19261. return geometry;
  19262. };
  19263. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19264. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19265. mesh.id = parsedMesh.id;
  19266. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19267. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19268. if (parsedMesh.rotationQuaternion) {
  19269. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19270. }
  19271. else if (parsedMesh.rotation) {
  19272. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19273. }
  19274. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19275. if (parsedMesh.localMatrix) {
  19276. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19277. }
  19278. else if (parsedMesh.pivotMatrix) {
  19279. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19280. }
  19281. mesh.setEnabled(parsedMesh.isEnabled);
  19282. mesh.isVisible = parsedMesh.isVisible;
  19283. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19284. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19285. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19286. if (parsedMesh.applyFog !== undefined) {
  19287. mesh.applyFog = parsedMesh.applyFog;
  19288. }
  19289. if (parsedMesh.pickable !== undefined) {
  19290. mesh.isPickable = parsedMesh.pickable;
  19291. }
  19292. if (parsedMesh.alphaIndex !== undefined) {
  19293. mesh.alphaIndex = parsedMesh.alphaIndex;
  19294. }
  19295. mesh.receiveShadows = parsedMesh.receiveShadows;
  19296. mesh.billboardMode = parsedMesh.billboardMode;
  19297. if (parsedMesh.visibility !== undefined) {
  19298. mesh.visibility = parsedMesh.visibility;
  19299. }
  19300. mesh.checkCollisions = parsedMesh.checkCollisions;
  19301. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19302. // Parent
  19303. if (parsedMesh.parentId) {
  19304. mesh._waitingParentId = parsedMesh.parentId;
  19305. }
  19306. // Actions
  19307. if (parsedMesh.actions !== undefined) {
  19308. mesh._waitingActions = parsedMesh.actions;
  19309. }
  19310. // Geometry
  19311. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19312. if (parsedMesh.delayLoadingFile) {
  19313. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19314. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19315. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19316. if (parsedMesh._binaryInfo) {
  19317. mesh._binaryInfo = parsedMesh._binaryInfo;
  19318. }
  19319. mesh._delayInfo = [];
  19320. if (parsedMesh.hasUVs) {
  19321. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19322. }
  19323. if (parsedMesh.hasUVs2) {
  19324. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19325. }
  19326. if (parsedMesh.hasColors) {
  19327. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19328. }
  19329. if (parsedMesh.hasMatricesIndices) {
  19330. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19331. }
  19332. if (parsedMesh.hasMatricesWeights) {
  19333. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19334. }
  19335. mesh._delayLoadingFunction = importGeometry;
  19336. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19337. mesh._checkDelayState();
  19338. }
  19339. }
  19340. else {
  19341. importGeometry(parsedMesh, mesh);
  19342. }
  19343. // Material
  19344. if (parsedMesh.materialId) {
  19345. mesh.setMaterialByID(parsedMesh.materialId);
  19346. }
  19347. else {
  19348. mesh.material = null;
  19349. }
  19350. // Skeleton
  19351. if (parsedMesh.skeletonId > -1) {
  19352. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19353. }
  19354. // Physics
  19355. if (parsedMesh.physicsImpostor) {
  19356. if (!scene.isPhysicsEnabled()) {
  19357. scene.enablePhysics();
  19358. }
  19359. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19360. }
  19361. // Animations
  19362. if (parsedMesh.animations) {
  19363. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19364. var parsedAnimation = parsedMesh.animations[animationIndex];
  19365. mesh.animations.push(parseAnimation(parsedAnimation));
  19366. }
  19367. }
  19368. if (parsedMesh.autoAnimate) {
  19369. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19370. }
  19371. // Layer Mask
  19372. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19373. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19374. }
  19375. else {
  19376. mesh.layerMask = 0xFFFFFFFF;
  19377. }
  19378. // Instances
  19379. if (parsedMesh.instances) {
  19380. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19381. var parsedInstance = parsedMesh.instances[index];
  19382. var instance = mesh.createInstance(parsedInstance.name);
  19383. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19384. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19385. if (parsedInstance.rotationQuaternion) {
  19386. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19387. }
  19388. else if (parsedInstance.rotation) {
  19389. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19390. }
  19391. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19392. instance.checkCollisions = mesh.checkCollisions;
  19393. if (parsedMesh.animations) {
  19394. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19395. parsedAnimation = parsedMesh.animations[animationIndex];
  19396. instance.animations.push(parseAnimation(parsedAnimation));
  19397. }
  19398. }
  19399. }
  19400. }
  19401. return mesh;
  19402. };
  19403. var parseActions = function (parsedActions, object, scene) {
  19404. var actionManager = new BABYLON.ActionManager(scene);
  19405. if (object === null)
  19406. scene.actionManager = actionManager;
  19407. else
  19408. object.actionManager = actionManager;
  19409. // instanciate a new object
  19410. var instanciate = function (name, params) {
  19411. var newInstance = Object.create(BABYLON[name].prototype);
  19412. newInstance.constructor.apply(newInstance, params);
  19413. return newInstance;
  19414. };
  19415. var parseParameter = function (name, value, target, propertyPath) {
  19416. if (propertyPath === null) {
  19417. // String, boolean or float
  19418. var floatValue = parseFloat(value);
  19419. if (value === "true" || value === "false")
  19420. return value === "true";
  19421. else
  19422. return isNaN(floatValue) ? value : floatValue;
  19423. }
  19424. var effectiveTarget = propertyPath.split(".");
  19425. var values = value.split(",");
  19426. // Get effective Target
  19427. for (var i = 0; i < effectiveTarget.length; i++) {
  19428. target = target[effectiveTarget[i]];
  19429. }
  19430. // Return appropriate value with its type
  19431. if (typeof (target) === "boolean")
  19432. return values[0] === "true";
  19433. if (typeof (target) === "string")
  19434. return values[0];
  19435. // Parameters with multiple values such as Vector3 etc.
  19436. var split = new Array();
  19437. for (var i = 0; i < values.length; i++)
  19438. split.push(parseFloat(values[i]));
  19439. if (target instanceof BABYLON.Vector3)
  19440. return BABYLON.Vector3.FromArray(split);
  19441. if (target instanceof BABYLON.Vector4)
  19442. return BABYLON.Vector4.FromArray(split);
  19443. if (target instanceof BABYLON.Color3)
  19444. return BABYLON.Color3.FromArray(split);
  19445. if (target instanceof BABYLON.Color4)
  19446. return BABYLON.Color4.FromArray(split);
  19447. return parseFloat(values[0]);
  19448. };
  19449. // traverse graph per trigger
  19450. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19451. if (combineArray === void 0) { combineArray = null; }
  19452. if (parsedAction.detached)
  19453. return;
  19454. var parameters = new Array();
  19455. var target = null;
  19456. var propertyPath = null;
  19457. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19458. // Parameters
  19459. if (parsedAction.type === 2)
  19460. parameters.push(actionManager);
  19461. else
  19462. parameters.push(trigger);
  19463. if (combine) {
  19464. var actions = new Array();
  19465. for (var j = 0; j < parsedAction.combine.length; j++) {
  19466. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19467. }
  19468. parameters.push(actions);
  19469. }
  19470. else {
  19471. for (var i = 0; i < parsedAction.properties.length; i++) {
  19472. var value = parsedAction.properties[i].value;
  19473. var name = parsedAction.properties[i].name;
  19474. var targetType = parsedAction.properties[i].targetType;
  19475. if (name === "target")
  19476. if (targetType !== null && targetType === "SceneProperties")
  19477. value = target = scene;
  19478. else
  19479. value = target = scene.getNodeByName(value);
  19480. else if (name === "parent")
  19481. value = scene.getNodeByName(value);
  19482. else if (name === "sound")
  19483. value = scene.getSoundByName(value);
  19484. else if (name !== "propertyPath") {
  19485. if (parsedAction.type === 2 && name === "operator")
  19486. value = BABYLON.ValueCondition[value];
  19487. else
  19488. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19489. }
  19490. else {
  19491. propertyPath = value;
  19492. }
  19493. parameters.push(value);
  19494. }
  19495. }
  19496. if (combineArray === null) {
  19497. parameters.push(condition);
  19498. }
  19499. else {
  19500. parameters.push(null);
  19501. }
  19502. // If interpolate value action
  19503. if (parsedAction.name === "InterpolateValueAction") {
  19504. var param = parameters[parameters.length - 2];
  19505. parameters[parameters.length - 1] = param;
  19506. parameters[parameters.length - 2] = condition;
  19507. }
  19508. // Action or condition(s) and not CombineAction
  19509. var newAction = instanciate(parsedAction.name, parameters);
  19510. if (combineArray === null) {
  19511. if (newAction instanceof BABYLON.Condition) {
  19512. condition = newAction;
  19513. newAction = action;
  19514. }
  19515. else {
  19516. condition = null;
  19517. if (action)
  19518. action.then(newAction);
  19519. else
  19520. actionManager.registerAction(newAction);
  19521. }
  19522. }
  19523. else {
  19524. combineArray.push(newAction);
  19525. }
  19526. for (var i = 0; i < parsedAction.children.length; i++)
  19527. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19528. };
  19529. // triggers
  19530. for (var i = 0; i < parsedActions.children.length; i++) {
  19531. var triggerParams;
  19532. var trigger = parsedActions.children[i];
  19533. if (trigger.properties.length > 0) {
  19534. var param = trigger.properties[0].value;
  19535. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  19536. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  19537. }
  19538. else
  19539. triggerParams = BABYLON.ActionManager[trigger.name];
  19540. for (var j = 0; j < trigger.children.length; j++) {
  19541. if (!trigger.detached)
  19542. traverse(trigger.children[j], triggerParams, null, null);
  19543. }
  19544. }
  19545. };
  19546. var parseSound = function (parsedSound, scene, rootUrl) {
  19547. var soundName = parsedSound.name;
  19548. var soundUrl = rootUrl + soundName;
  19549. var options = {
  19550. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  19551. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  19552. rolloffFactor: parsedSound.rolloffFactor,
  19553. refDistance: parsedSound.refDistance,
  19554. distanceModel: parsedSound.distanceModel,
  19555. playbackRate: parsedSound.playbackRate
  19556. };
  19557. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  19558. scene._addPendingData(newSound);
  19559. if (parsedSound.position) {
  19560. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19561. newSound.setPosition(soundPosition);
  19562. }
  19563. if (parsedSound.isDirectional) {
  19564. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19565. if (parsedSound.localDirectionToMesh) {
  19566. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19567. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19568. }
  19569. }
  19570. if (parsedSound.connectedMeshId) {
  19571. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19572. if (connectedMesh) {
  19573. newSound.attachToMesh(connectedMesh);
  19574. }
  19575. }
  19576. };
  19577. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19578. names = (names instanceof Array) ? names : [names];
  19579. for (var i in names) {
  19580. if (mesh.name === names[i]) {
  19581. hierarchyIds.push(mesh.id);
  19582. return true;
  19583. }
  19584. }
  19585. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19586. hierarchyIds.push(mesh.id);
  19587. return true;
  19588. }
  19589. return false;
  19590. };
  19591. var importVertexData = function (parsedVertexData, geometry) {
  19592. var vertexData = new BABYLON.VertexData();
  19593. // positions
  19594. var positions = parsedVertexData.positions;
  19595. if (positions) {
  19596. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19597. }
  19598. // normals
  19599. var normals = parsedVertexData.normals;
  19600. if (normals) {
  19601. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19602. }
  19603. // uvs
  19604. var uvs = parsedVertexData.uvs;
  19605. if (uvs) {
  19606. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19607. }
  19608. // uv2s
  19609. var uv2s = parsedVertexData.uv2s;
  19610. if (uv2s) {
  19611. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19612. }
  19613. // colors
  19614. var colors = parsedVertexData.colors;
  19615. if (colors) {
  19616. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19617. }
  19618. // matricesIndices
  19619. var matricesIndices = parsedVertexData.matricesIndices;
  19620. if (matricesIndices) {
  19621. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19622. }
  19623. // matricesWeights
  19624. var matricesWeights = parsedVertexData.matricesWeights;
  19625. if (matricesWeights) {
  19626. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19627. }
  19628. // indices
  19629. var indices = parsedVertexData.indices;
  19630. if (indices) {
  19631. vertexData.indices = indices;
  19632. }
  19633. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19634. };
  19635. var importGeometry = function (parsedGeometry, mesh) {
  19636. var scene = mesh.getScene();
  19637. // Geometry
  19638. var geometryId = parsedGeometry.geometryId;
  19639. if (geometryId) {
  19640. var geometry = scene.getGeometryByID(geometryId);
  19641. if (geometry) {
  19642. geometry.applyToMesh(mesh);
  19643. }
  19644. }
  19645. else if (parsedGeometry instanceof ArrayBuffer) {
  19646. var binaryInfo = mesh._binaryInfo;
  19647. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19648. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19649. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19650. }
  19651. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19652. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19653. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19654. }
  19655. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19656. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19657. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19658. }
  19659. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19660. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19661. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19662. }
  19663. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19664. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19665. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19666. }
  19667. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19668. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19669. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19670. }
  19671. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19672. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19673. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19674. }
  19675. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19676. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19677. mesh.setIndices(indicesData);
  19678. }
  19679. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19680. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19681. mesh.subMeshes = [];
  19682. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19683. var materialIndex = subMeshesData[(i * 5) + 0];
  19684. var verticesStart = subMeshesData[(i * 5) + 1];
  19685. var verticesCount = subMeshesData[(i * 5) + 2];
  19686. var indexStart = subMeshesData[(i * 5) + 3];
  19687. var indexCount = subMeshesData[(i * 5) + 4];
  19688. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19689. }
  19690. }
  19691. }
  19692. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19693. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19694. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19695. if (parsedGeometry.uvs) {
  19696. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19697. }
  19698. if (parsedGeometry.uvs2) {
  19699. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19700. }
  19701. if (parsedGeometry.colors) {
  19702. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19703. }
  19704. if (parsedGeometry.matricesIndices) {
  19705. if (!parsedGeometry.matricesIndices._isExpanded) {
  19706. var floatIndices = [];
  19707. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19708. var matricesIndex = parsedGeometry.matricesIndices[i];
  19709. floatIndices.push(matricesIndex & 0x000000FF);
  19710. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19711. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19712. floatIndices.push(matricesIndex >> 24);
  19713. }
  19714. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19715. }
  19716. else {
  19717. delete parsedGeometry.matricesIndices._isExpanded;
  19718. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19719. }
  19720. }
  19721. if (parsedGeometry.matricesWeights) {
  19722. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19723. }
  19724. mesh.setIndices(parsedGeometry.indices);
  19725. // SubMeshes
  19726. if (parsedGeometry.subMeshes) {
  19727. mesh.subMeshes = [];
  19728. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19729. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19730. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19731. }
  19732. }
  19733. }
  19734. // Flat shading
  19735. if (mesh._shouldGenerateFlatShading) {
  19736. mesh.convertToFlatShadedMesh();
  19737. delete mesh._shouldGenerateFlatShading;
  19738. }
  19739. // Update
  19740. mesh.computeWorldMatrix(true);
  19741. // Octree
  19742. if (scene._selectionOctree) {
  19743. scene._selectionOctree.addMesh(mesh);
  19744. }
  19745. };
  19746. BABYLON.SceneLoader.RegisterPlugin({
  19747. extensions: ".babylon",
  19748. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19749. var parsedData = JSON.parse(data);
  19750. var loadedSkeletonsIds = [];
  19751. var loadedMaterialsIds = [];
  19752. var hierarchyIds = [];
  19753. for (var index = 0; index < parsedData.meshes.length; index++) {
  19754. var parsedMesh = parsedData.meshes[index];
  19755. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19756. if (meshesNames instanceof Array) {
  19757. // Remove found mesh name from list.
  19758. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19759. }
  19760. //Geometry?
  19761. if (parsedMesh.geometryId) {
  19762. //does the file contain geometries?
  19763. if (parsedData.geometries) {
  19764. //find the correct geometry and add it to the scene
  19765. var found = false;
  19766. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  19767. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  19768. return;
  19769. }
  19770. else {
  19771. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  19772. if (parsedGeometryData.id == parsedMesh.geometryId) {
  19773. switch (geometryType) {
  19774. case "boxes":
  19775. parseBox(parsedGeometryData, scene);
  19776. break;
  19777. case "spheres":
  19778. parseSphere(parsedGeometryData, scene);
  19779. break;
  19780. case "cylinders":
  19781. parseCylinder(parsedGeometryData, scene);
  19782. break;
  19783. case "toruses":
  19784. parseTorus(parsedGeometryData, scene);
  19785. break;
  19786. case "grounds":
  19787. parseGround(parsedGeometryData, scene);
  19788. break;
  19789. case "planes":
  19790. parsePlane(parsedGeometryData, scene);
  19791. break;
  19792. case "torusKnots":
  19793. parseTorusKnot(parsedGeometryData, scene);
  19794. break;
  19795. case "vertexData":
  19796. parseVertexData(parsedGeometryData, scene, rootUrl);
  19797. break;
  19798. }
  19799. found = true;
  19800. }
  19801. });
  19802. }
  19803. });
  19804. }
  19805. }
  19806. // Material ?
  19807. if (parsedMesh.materialId) {
  19808. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19809. if (!materialFound) {
  19810. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19811. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19812. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19813. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19814. var subMatId = parsedMultiMaterial.materials[matIndex];
  19815. loadedMaterialsIds.push(subMatId);
  19816. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19817. }
  19818. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19819. parseMultiMaterial(parsedMultiMaterial, scene);
  19820. materialFound = true;
  19821. break;
  19822. }
  19823. }
  19824. }
  19825. if (!materialFound) {
  19826. loadedMaterialsIds.push(parsedMesh.materialId);
  19827. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19828. }
  19829. }
  19830. // Skeleton ?
  19831. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19832. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19833. if (!skeletonAlreadyLoaded) {
  19834. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19835. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19836. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19837. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19838. loadedSkeletonsIds.push(parsedSkeleton.id);
  19839. }
  19840. }
  19841. }
  19842. }
  19843. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19844. meshes.push(mesh);
  19845. }
  19846. }
  19847. // Connecting parents
  19848. for (index = 0; index < scene.meshes.length; index++) {
  19849. var currentMesh = scene.meshes[index];
  19850. if (currentMesh._waitingParentId) {
  19851. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19852. currentMesh._waitingParentId = undefined;
  19853. }
  19854. }
  19855. // Particles
  19856. if (parsedData.particleSystems) {
  19857. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19858. var parsedParticleSystem = parsedData.particleSystems[index];
  19859. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19860. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19861. }
  19862. }
  19863. }
  19864. return true;
  19865. },
  19866. load: function (scene, data, rootUrl) {
  19867. var parsedData = JSON.parse(data);
  19868. // Scene
  19869. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19870. scene.autoClear = parsedData.autoClear;
  19871. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19872. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19873. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19874. // Fog
  19875. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19876. scene.fogMode = parsedData.fogMode;
  19877. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19878. scene.fogStart = parsedData.fogStart;
  19879. scene.fogEnd = parsedData.fogEnd;
  19880. scene.fogDensity = parsedData.fogDensity;
  19881. }
  19882. // Lights
  19883. for (var index = 0; index < parsedData.lights.length; index++) {
  19884. var parsedLight = parsedData.lights[index];
  19885. parseLight(parsedLight, scene);
  19886. }
  19887. // Materials
  19888. if (parsedData.materials) {
  19889. for (index = 0; index < parsedData.materials.length; index++) {
  19890. var parsedMaterial = parsedData.materials[index];
  19891. parseMaterial(parsedMaterial, scene, rootUrl);
  19892. }
  19893. }
  19894. if (parsedData.multiMaterials) {
  19895. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19896. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19897. parseMultiMaterial(parsedMultiMaterial, scene);
  19898. }
  19899. }
  19900. // Skeletons
  19901. if (parsedData.skeletons) {
  19902. for (index = 0; index < parsedData.skeletons.length; index++) {
  19903. var parsedSkeleton = parsedData.skeletons[index];
  19904. parseSkeleton(parsedSkeleton, scene);
  19905. }
  19906. }
  19907. // Geometries
  19908. var geometries = parsedData.geometries;
  19909. if (geometries) {
  19910. // Boxes
  19911. var boxes = geometries.boxes;
  19912. if (boxes) {
  19913. for (index = 0; index < boxes.length; index++) {
  19914. var parsedBox = boxes[index];
  19915. parseBox(parsedBox, scene);
  19916. }
  19917. }
  19918. // Spheres
  19919. var spheres = geometries.spheres;
  19920. if (spheres) {
  19921. for (index = 0; index < spheres.length; index++) {
  19922. var parsedSphere = spheres[index];
  19923. parseSphere(parsedSphere, scene);
  19924. }
  19925. }
  19926. // Cylinders
  19927. var cylinders = geometries.cylinders;
  19928. if (cylinders) {
  19929. for (index = 0; index < cylinders.length; index++) {
  19930. var parsedCylinder = cylinders[index];
  19931. parseCylinder(parsedCylinder, scene);
  19932. }
  19933. }
  19934. // Toruses
  19935. var toruses = geometries.toruses;
  19936. if (toruses) {
  19937. for (index = 0; index < toruses.length; index++) {
  19938. var parsedTorus = toruses[index];
  19939. parseTorus(parsedTorus, scene);
  19940. }
  19941. }
  19942. // Grounds
  19943. var grounds = geometries.grounds;
  19944. if (grounds) {
  19945. for (index = 0; index < grounds.length; index++) {
  19946. var parsedGround = grounds[index];
  19947. parseGround(parsedGround, scene);
  19948. }
  19949. }
  19950. // Planes
  19951. var planes = geometries.planes;
  19952. if (planes) {
  19953. for (index = 0; index < planes.length; index++) {
  19954. var parsedPlane = planes[index];
  19955. parsePlane(parsedPlane, scene);
  19956. }
  19957. }
  19958. // TorusKnots
  19959. var torusKnots = geometries.torusKnots;
  19960. if (torusKnots) {
  19961. for (index = 0; index < torusKnots.length; index++) {
  19962. var parsedTorusKnot = torusKnots[index];
  19963. parseTorusKnot(parsedTorusKnot, scene);
  19964. }
  19965. }
  19966. // VertexData
  19967. var vertexData = geometries.vertexData;
  19968. if (vertexData) {
  19969. for (index = 0; index < vertexData.length; index++) {
  19970. var parsedVertexData = vertexData[index];
  19971. parseVertexData(parsedVertexData, scene, rootUrl);
  19972. }
  19973. }
  19974. }
  19975. // Meshes
  19976. for (index = 0; index < parsedData.meshes.length; index++) {
  19977. var parsedMesh = parsedData.meshes[index];
  19978. parseMesh(parsedMesh, scene, rootUrl);
  19979. }
  19980. // Cameras
  19981. for (index = 0; index < parsedData.cameras.length; index++) {
  19982. var parsedCamera = parsedData.cameras[index];
  19983. parseCamera(parsedCamera, scene);
  19984. }
  19985. if (parsedData.activeCameraID) {
  19986. scene.setActiveCameraByID(parsedData.activeCameraID);
  19987. }
  19988. // Browsing all the graph to connect the dots
  19989. for (index = 0; index < scene.cameras.length; index++) {
  19990. var camera = scene.cameras[index];
  19991. if (camera._waitingParentId) {
  19992. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19993. camera._waitingParentId = undefined;
  19994. }
  19995. }
  19996. for (index = 0; index < scene.lights.length; index++) {
  19997. var light = scene.lights[index];
  19998. if (light._waitingParentId) {
  19999. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20000. light._waitingParentId = undefined;
  20001. }
  20002. }
  20003. // Sounds
  20004. if (parsedData.sounds) {
  20005. for (index = 0; index < parsedData.sounds.length; index++) {
  20006. var parsedSound = parsedData.sounds[index];
  20007. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20008. parseSound(parsedSound, scene, rootUrl);
  20009. }
  20010. else {
  20011. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20012. }
  20013. }
  20014. }
  20015. // Connect parents & children and parse actions
  20016. for (index = 0; index < scene.meshes.length; index++) {
  20017. var mesh = scene.meshes[index];
  20018. if (mesh._waitingParentId) {
  20019. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20020. mesh._waitingParentId = undefined;
  20021. }
  20022. if (mesh._waitingActions) {
  20023. parseActions(mesh._waitingActions, mesh, scene);
  20024. mesh._waitingActions = undefined;
  20025. }
  20026. }
  20027. // Particles Systems
  20028. if (parsedData.particleSystems) {
  20029. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20030. var parsedParticleSystem = parsedData.particleSystems[index];
  20031. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20032. }
  20033. }
  20034. // Lens flares
  20035. if (parsedData.lensFlareSystems) {
  20036. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20037. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20038. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20039. }
  20040. }
  20041. // Shadows
  20042. if (parsedData.shadowGenerators) {
  20043. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20044. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20045. parseShadowGenerator(parsedShadowGenerator, scene);
  20046. }
  20047. }
  20048. // Actions (scene)
  20049. if (parsedData.actions) {
  20050. parseActions(parsedData.actions, null, scene);
  20051. }
  20052. // Finish
  20053. return true;
  20054. }
  20055. });
  20056. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20057. })(BABYLON || (BABYLON = {}));
  20058. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  20059. var BABYLON;
  20060. (function (BABYLON) {
  20061. var SpriteManager = (function () {
  20062. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20063. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20064. this.name = name;
  20065. this.cellSize = cellSize;
  20066. this.sprites = new Array();
  20067. this.renderingGroupId = 0;
  20068. this.fogEnabled = true;
  20069. this._vertexDeclaration = [4, 4, 4, 4];
  20070. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20071. this._capacity = capacity;
  20072. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20073. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20074. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20075. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20076. this._scene = scene;
  20077. this._scene.spriteManagers.push(this);
  20078. // VBO
  20079. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20080. var indices = [];
  20081. var index = 0;
  20082. for (var count = 0; count < capacity; count++) {
  20083. indices.push(index);
  20084. indices.push(index + 1);
  20085. indices.push(index + 2);
  20086. indices.push(index);
  20087. indices.push(index + 2);
  20088. indices.push(index + 3);
  20089. index += 4;
  20090. }
  20091. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20092. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20093. // Effects
  20094. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20095. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20096. }
  20097. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20098. var arrayOffset = index * 16;
  20099. if (offsetX === 0)
  20100. offsetX = this._epsilon;
  20101. else if (offsetX === 1)
  20102. offsetX = 1 - this._epsilon;
  20103. if (offsetY === 0)
  20104. offsetY = this._epsilon;
  20105. else if (offsetY === 1)
  20106. offsetY = 1 - this._epsilon;
  20107. this._vertices[arrayOffset] = sprite.position.x;
  20108. this._vertices[arrayOffset + 1] = sprite.position.y;
  20109. this._vertices[arrayOffset + 2] = sprite.position.z;
  20110. this._vertices[arrayOffset + 3] = sprite.angle;
  20111. this._vertices[arrayOffset + 4] = sprite.width;
  20112. this._vertices[arrayOffset + 5] = sprite.height;
  20113. this._vertices[arrayOffset + 6] = offsetX;
  20114. this._vertices[arrayOffset + 7] = offsetY;
  20115. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20116. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20117. var offset = (sprite.cellIndex / rowSize) >> 0;
  20118. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20119. this._vertices[arrayOffset + 11] = offset;
  20120. // Color
  20121. this._vertices[arrayOffset + 12] = sprite.color.r;
  20122. this._vertices[arrayOffset + 13] = sprite.color.g;
  20123. this._vertices[arrayOffset + 14] = sprite.color.b;
  20124. this._vertices[arrayOffset + 15] = sprite.color.a;
  20125. };
  20126. SpriteManager.prototype.render = function () {
  20127. // Check
  20128. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20129. return;
  20130. var engine = this._scene.getEngine();
  20131. var baseSize = this._spriteTexture.getBaseSize();
  20132. // Sprites
  20133. var deltaTime = engine.getDeltaTime();
  20134. var max = Math.min(this._capacity, this.sprites.length);
  20135. var rowSize = baseSize.width / this.cellSize;
  20136. var offset = 0;
  20137. for (var index = 0; index < max; index++) {
  20138. var sprite = this.sprites[index];
  20139. if (!sprite) {
  20140. continue;
  20141. }
  20142. sprite._animate(deltaTime);
  20143. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20144. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20145. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20146. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20147. }
  20148. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20149. // Render
  20150. var effect = this._effectBase;
  20151. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20152. effect = this._effectFog;
  20153. }
  20154. engine.enableEffect(effect);
  20155. var viewMatrix = this._scene.getViewMatrix();
  20156. effect.setTexture("diffuseSampler", this._spriteTexture);
  20157. effect.setMatrix("view", viewMatrix);
  20158. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20159. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20160. // Fog
  20161. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20162. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20163. effect.setColor3("vFogColor", this._scene.fogColor);
  20164. }
  20165. // VBOs
  20166. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20167. // Draw order
  20168. engine.setDepthFunctionToLessOrEqual();
  20169. effect.setBool("alphaTest", true);
  20170. engine.setColorWrite(false);
  20171. engine.draw(true, 0, max * 6);
  20172. engine.setColorWrite(true);
  20173. effect.setBool("alphaTest", false);
  20174. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20175. engine.draw(true, 0, max * 6);
  20176. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20177. };
  20178. SpriteManager.prototype.dispose = function () {
  20179. if (this._vertexBuffer) {
  20180. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20181. this._vertexBuffer = null;
  20182. }
  20183. if (this._indexBuffer) {
  20184. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20185. this._indexBuffer = null;
  20186. }
  20187. if (this._spriteTexture) {
  20188. this._spriteTexture.dispose();
  20189. this._spriteTexture = null;
  20190. }
  20191. // Remove from scene
  20192. var index = this._scene.spriteManagers.indexOf(this);
  20193. this._scene.spriteManagers.splice(index, 1);
  20194. // Callback
  20195. if (this.onDispose) {
  20196. this.onDispose();
  20197. }
  20198. };
  20199. return SpriteManager;
  20200. })();
  20201. BABYLON.SpriteManager = SpriteManager;
  20202. })(BABYLON || (BABYLON = {}));
  20203. //# sourceMappingURL=babylon.spriteManager.js.map
  20204. var BABYLON;
  20205. (function (BABYLON) {
  20206. var Sprite = (function () {
  20207. function Sprite(name, manager) {
  20208. this.name = name;
  20209. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20210. this.width = 1.0;
  20211. this.height = 1.0;
  20212. this.angle = 0;
  20213. this.cellIndex = 0;
  20214. this.invertU = 0;
  20215. this.invertV = 0;
  20216. this.animations = new Array();
  20217. this._animationStarted = false;
  20218. this._loopAnimation = false;
  20219. this._fromIndex = 0;
  20220. this._toIndex = 0;
  20221. this._delay = 0;
  20222. this._direction = 1;
  20223. this._frameCount = 0;
  20224. this._time = 0;
  20225. this._manager = manager;
  20226. this._manager.sprites.push(this);
  20227. this.position = BABYLON.Vector3.Zero();
  20228. }
  20229. Object.defineProperty(Sprite.prototype, "size", {
  20230. get: function () {
  20231. return this.width;
  20232. },
  20233. set: function (value) {
  20234. this.width = value;
  20235. this.height = value;
  20236. },
  20237. enumerable: true,
  20238. configurable: true
  20239. });
  20240. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20241. this._fromIndex = from;
  20242. this._toIndex = to;
  20243. this._loopAnimation = loop;
  20244. this._delay = delay;
  20245. this._animationStarted = true;
  20246. this._direction = from < to ? 1 : -1;
  20247. this.cellIndex = from;
  20248. this._time = 0;
  20249. };
  20250. Sprite.prototype.stopAnimation = function () {
  20251. this._animationStarted = false;
  20252. };
  20253. Sprite.prototype._animate = function (deltaTime) {
  20254. if (!this._animationStarted)
  20255. return;
  20256. this._time += deltaTime;
  20257. if (this._time > this._delay) {
  20258. this._time = this._time % this._delay;
  20259. this.cellIndex += this._direction;
  20260. if (this.cellIndex == this._toIndex) {
  20261. if (this._loopAnimation) {
  20262. this.cellIndex = this._fromIndex;
  20263. }
  20264. else {
  20265. this._animationStarted = false;
  20266. if (this.disposeWhenFinishedAnimating) {
  20267. this.dispose();
  20268. }
  20269. }
  20270. }
  20271. }
  20272. };
  20273. Sprite.prototype.dispose = function () {
  20274. for (var i = 0; i < this._manager.sprites.length; i++) {
  20275. if (this._manager.sprites[i] == this) {
  20276. this._manager.sprites.splice(i, 1);
  20277. }
  20278. }
  20279. };
  20280. return Sprite;
  20281. })();
  20282. BABYLON.Sprite = Sprite;
  20283. })(BABYLON || (BABYLON = {}));
  20284. //# sourceMappingURL=babylon.sprite.js.map
  20285. var BABYLON;
  20286. (function (BABYLON) {
  20287. var Layer = (function () {
  20288. function Layer(name, imgUrl, scene, isBackground, color) {
  20289. this.name = name;
  20290. this._vertexDeclaration = [2];
  20291. this._vertexStrideSize = 2 * 4;
  20292. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20293. this.isBackground = isBackground === undefined ? true : isBackground;
  20294. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20295. this._scene = scene;
  20296. this._scene.layers.push(this);
  20297. // VBO
  20298. var vertices = [];
  20299. vertices.push(1, 1);
  20300. vertices.push(-1, 1);
  20301. vertices.push(-1, -1);
  20302. vertices.push(1, -1);
  20303. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20304. // Indices
  20305. var indices = [];
  20306. indices.push(0);
  20307. indices.push(1);
  20308. indices.push(2);
  20309. indices.push(0);
  20310. indices.push(2);
  20311. indices.push(3);
  20312. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20313. // Effects
  20314. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20315. }
  20316. Layer.prototype.render = function () {
  20317. // Check
  20318. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20319. return;
  20320. var engine = this._scene.getEngine();
  20321. // Render
  20322. engine.enableEffect(this._effect);
  20323. engine.setState(false);
  20324. // Texture
  20325. this._effect.setTexture("textureSampler", this.texture);
  20326. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20327. // Color
  20328. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20329. // VBOs
  20330. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20331. // Draw order
  20332. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20333. engine.draw(true, 0, 6);
  20334. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20335. };
  20336. Layer.prototype.dispose = function () {
  20337. if (this._vertexBuffer) {
  20338. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20339. this._vertexBuffer = null;
  20340. }
  20341. if (this._indexBuffer) {
  20342. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20343. this._indexBuffer = null;
  20344. }
  20345. if (this.texture) {
  20346. this.texture.dispose();
  20347. this.texture = null;
  20348. }
  20349. // Remove from scene
  20350. var index = this._scene.layers.indexOf(this);
  20351. this._scene.layers.splice(index, 1);
  20352. // Callback
  20353. if (this.onDispose) {
  20354. this.onDispose();
  20355. }
  20356. };
  20357. return Layer;
  20358. })();
  20359. BABYLON.Layer = Layer;
  20360. })(BABYLON || (BABYLON = {}));
  20361. //# sourceMappingURL=babylon.layer.js.map
  20362. var BABYLON;
  20363. (function (BABYLON) {
  20364. var Particle = (function () {
  20365. function Particle() {
  20366. this.position = BABYLON.Vector3.Zero();
  20367. this.direction = BABYLON.Vector3.Zero();
  20368. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20369. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20370. this.lifeTime = 1.0;
  20371. this.age = 0;
  20372. this.size = 0;
  20373. this.angle = 0;
  20374. this.angularSpeed = 0;
  20375. }
  20376. Particle.prototype.copyTo = function (other) {
  20377. other.position.copyFrom(this.position);
  20378. other.direction.copyFrom(this.direction);
  20379. other.color.copyFrom(this.color);
  20380. other.colorStep.copyFrom(this.colorStep);
  20381. other.lifeTime = this.lifeTime;
  20382. other.age = this.age;
  20383. other.size = this.size;
  20384. other.angle = this.angle;
  20385. other.angularSpeed = this.angularSpeed;
  20386. };
  20387. return Particle;
  20388. })();
  20389. BABYLON.Particle = Particle;
  20390. })(BABYLON || (BABYLON = {}));
  20391. //# sourceMappingURL=babylon.particle.js.map
  20392. var BABYLON;
  20393. (function (BABYLON) {
  20394. var randomNumber = function (min, max) {
  20395. if (min === max) {
  20396. return (min);
  20397. }
  20398. var random = Math.random();
  20399. return ((random * (max - min)) + min);
  20400. };
  20401. var ParticleSystem = (function () {
  20402. function ParticleSystem(name, capacity, scene, customEffect) {
  20403. var _this = this;
  20404. this.name = name;
  20405. this.renderingGroupId = 0;
  20406. this.emitter = null;
  20407. this.emitRate = 10;
  20408. this.manualEmitCount = -1;
  20409. this.updateSpeed = 0.01;
  20410. this.targetStopDuration = 0;
  20411. this.disposeOnStop = false;
  20412. this.minEmitPower = 1;
  20413. this.maxEmitPower = 1;
  20414. this.minLifeTime = 1;
  20415. this.maxLifeTime = 1;
  20416. this.minSize = 1;
  20417. this.maxSize = 1;
  20418. this.minAngularSpeed = 0;
  20419. this.maxAngularSpeed = 0;
  20420. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20421. this.forceDepthWrite = false;
  20422. this.gravity = BABYLON.Vector3.Zero();
  20423. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20424. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20425. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20426. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20427. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20428. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20429. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20430. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20431. this.particles = new Array();
  20432. this._vertexDeclaration = [3, 4, 4];
  20433. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20434. this._stockParticles = new Array();
  20435. this._newPartsExcess = 0;
  20436. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20437. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20438. this._scaledDirection = BABYLON.Vector3.Zero();
  20439. this._scaledGravity = BABYLON.Vector3.Zero();
  20440. this._currentRenderId = -1;
  20441. this._started = false;
  20442. this._stopped = false;
  20443. this._actualFrame = 0;
  20444. this.id = name;
  20445. this._capacity = capacity;
  20446. this._scene = scene;
  20447. this._customEffect = customEffect;
  20448. scene.particleSystems.push(this);
  20449. // VBO
  20450. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20451. var indices = [];
  20452. var index = 0;
  20453. for (var count = 0; count < capacity; count++) {
  20454. indices.push(index);
  20455. indices.push(index + 1);
  20456. indices.push(index + 2);
  20457. indices.push(index);
  20458. indices.push(index + 2);
  20459. indices.push(index + 3);
  20460. index += 4;
  20461. }
  20462. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20463. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20464. // Default behaviors
  20465. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  20466. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20467. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20468. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20469. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20470. };
  20471. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  20472. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20473. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20474. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20475. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20476. };
  20477. this.updateFunction = function (particles) {
  20478. for (var index = 0; index < particles.length; index++) {
  20479. var particle = particles[index];
  20480. particle.age += _this._scaledUpdateSpeed;
  20481. if (particle.age >= particle.lifeTime) {
  20482. _this.recycleParticle(particle);
  20483. index--;
  20484. continue;
  20485. }
  20486. else {
  20487. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20488. particle.color.addInPlace(_this._scaledColorStep);
  20489. if (particle.color.a < 0)
  20490. particle.color.a = 0;
  20491. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20492. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20493. particle.position.addInPlace(_this._scaledDirection);
  20494. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20495. particle.direction.addInPlace(_this._scaledGravity);
  20496. }
  20497. }
  20498. };
  20499. }
  20500. ParticleSystem.prototype.recycleParticle = function (particle) {
  20501. var lastParticle = this.particles.pop();
  20502. if (lastParticle !== particle) {
  20503. lastParticle.copyTo(particle);
  20504. this._stockParticles.push(lastParticle);
  20505. }
  20506. };
  20507. ParticleSystem.prototype.getCapacity = function () {
  20508. return this._capacity;
  20509. };
  20510. ParticleSystem.prototype.isAlive = function () {
  20511. return this._alive;
  20512. };
  20513. ParticleSystem.prototype.isStarted = function () {
  20514. return this._started;
  20515. };
  20516. ParticleSystem.prototype.start = function () {
  20517. this._started = true;
  20518. this._stopped = false;
  20519. this._actualFrame = 0;
  20520. };
  20521. ParticleSystem.prototype.stop = function () {
  20522. this._stopped = true;
  20523. };
  20524. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  20525. var offset = index * 11;
  20526. this._vertices[offset] = particle.position.x;
  20527. this._vertices[offset + 1] = particle.position.y;
  20528. this._vertices[offset + 2] = particle.position.z;
  20529. this._vertices[offset + 3] = particle.color.r;
  20530. this._vertices[offset + 4] = particle.color.g;
  20531. this._vertices[offset + 5] = particle.color.b;
  20532. this._vertices[offset + 6] = particle.color.a;
  20533. this._vertices[offset + 7] = particle.angle;
  20534. this._vertices[offset + 8] = particle.size;
  20535. this._vertices[offset + 9] = offsetX;
  20536. this._vertices[offset + 10] = offsetY;
  20537. };
  20538. ParticleSystem.prototype._update = function (newParticles) {
  20539. // Update current
  20540. this._alive = this.particles.length > 0;
  20541. this.updateFunction(this.particles);
  20542. // Add new ones
  20543. var worldMatrix;
  20544. if (this.emitter.position) {
  20545. worldMatrix = this.emitter.getWorldMatrix();
  20546. }
  20547. else {
  20548. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  20549. }
  20550. for (var index = 0; index < newParticles; index++) {
  20551. if (this.particles.length === this._capacity) {
  20552. break;
  20553. }
  20554. if (this._stockParticles.length !== 0) {
  20555. var particle = this._stockParticles.pop();
  20556. particle.age = 0;
  20557. }
  20558. else {
  20559. particle = new BABYLON.Particle();
  20560. }
  20561. this.particles.push(particle);
  20562. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  20563. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  20564. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  20565. particle.size = randomNumber(this.minSize, this.maxSize);
  20566. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  20567. this.startPositionFunction(worldMatrix, particle.position);
  20568. var step = randomNumber(0, 1.0);
  20569. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  20570. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  20571. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  20572. }
  20573. };
  20574. ParticleSystem.prototype._getEffect = function () {
  20575. if (this._customEffect) {
  20576. return this._customEffect;
  20577. }
  20578. ;
  20579. var defines = [];
  20580. if (this._scene.clipPlane) {
  20581. defines.push("#define CLIPPLANE");
  20582. }
  20583. // Effect
  20584. var join = defines.join("\n");
  20585. if (this._cachedDefines !== join) {
  20586. this._cachedDefines = join;
  20587. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  20588. }
  20589. return this._effect;
  20590. };
  20591. ParticleSystem.prototype.animate = function () {
  20592. if (!this._started)
  20593. return;
  20594. var effect = this._getEffect();
  20595. // Check
  20596. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  20597. return;
  20598. if (this._currentRenderId === this._scene.getRenderId()) {
  20599. return;
  20600. }
  20601. this._currentRenderId = this._scene.getRenderId();
  20602. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  20603. // determine the number of particles we need to create
  20604. var emitCout;
  20605. if (this.manualEmitCount > -1) {
  20606. emitCout = this.manualEmitCount;
  20607. this.manualEmitCount = 0;
  20608. }
  20609. else {
  20610. emitCout = this.emitRate;
  20611. }
  20612. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  20613. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  20614. if (this._newPartsExcess > 1.0) {
  20615. newParticles += this._newPartsExcess >> 0;
  20616. this._newPartsExcess -= this._newPartsExcess >> 0;
  20617. }
  20618. this._alive = false;
  20619. if (!this._stopped) {
  20620. this._actualFrame += this._scaledUpdateSpeed;
  20621. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  20622. this.stop();
  20623. }
  20624. else {
  20625. newParticles = 0;
  20626. }
  20627. this._update(newParticles);
  20628. // Stopped?
  20629. if (this._stopped) {
  20630. if (!this._alive) {
  20631. this._started = false;
  20632. if (this.disposeOnStop) {
  20633. this._scene._toBeDisposed.push(this);
  20634. }
  20635. }
  20636. }
  20637. // Update VBO
  20638. var offset = 0;
  20639. for (var index = 0; index < this.particles.length; index++) {
  20640. var particle = this.particles[index];
  20641. this._appendParticleVertex(offset++, particle, 0, 0);
  20642. this._appendParticleVertex(offset++, particle, 1, 0);
  20643. this._appendParticleVertex(offset++, particle, 1, 1);
  20644. this._appendParticleVertex(offset++, particle, 0, 1);
  20645. }
  20646. var engine = this._scene.getEngine();
  20647. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20648. };
  20649. ParticleSystem.prototype.render = function () {
  20650. var effect = this._getEffect();
  20651. // Check
  20652. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  20653. return 0;
  20654. var engine = this._scene.getEngine();
  20655. // Render
  20656. engine.enableEffect(effect);
  20657. engine.setState(false);
  20658. var viewMatrix = this._scene.getViewMatrix();
  20659. effect.setTexture("diffuseSampler", this.particleTexture);
  20660. effect.setMatrix("view", viewMatrix);
  20661. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20662. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  20663. if (this._scene.clipPlane) {
  20664. var clipPlane = this._scene.clipPlane;
  20665. var invView = viewMatrix.clone();
  20666. invView.invert();
  20667. effect.setMatrix("invView", invView);
  20668. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20669. }
  20670. // VBOs
  20671. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20672. // Draw order
  20673. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  20674. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  20675. }
  20676. else {
  20677. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20678. }
  20679. if (this.forceDepthWrite) {
  20680. engine.setDepthWrite(true);
  20681. }
  20682. engine.draw(true, 0, this.particles.length * 6);
  20683. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20684. return this.particles.length;
  20685. };
  20686. ParticleSystem.prototype.dispose = function () {
  20687. if (this._vertexBuffer) {
  20688. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20689. this._vertexBuffer = null;
  20690. }
  20691. if (this._indexBuffer) {
  20692. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20693. this._indexBuffer = null;
  20694. }
  20695. if (this.particleTexture) {
  20696. this.particleTexture.dispose();
  20697. this.particleTexture = null;
  20698. }
  20699. // Remove from scene
  20700. var index = this._scene.particleSystems.indexOf(this);
  20701. this._scene.particleSystems.splice(index, 1);
  20702. // Callback
  20703. if (this.onDispose) {
  20704. this.onDispose();
  20705. }
  20706. };
  20707. // Clone
  20708. ParticleSystem.prototype.clone = function (name, newEmitter) {
  20709. var result = new ParticleSystem(name, this._capacity, this._scene);
  20710. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  20711. if (newEmitter === undefined) {
  20712. newEmitter = this.emitter;
  20713. }
  20714. result.emitter = newEmitter;
  20715. if (this.particleTexture) {
  20716. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  20717. }
  20718. result.start();
  20719. return result;
  20720. };
  20721. // Statics
  20722. ParticleSystem.BLENDMODE_ONEONE = 0;
  20723. ParticleSystem.BLENDMODE_STANDARD = 1;
  20724. return ParticleSystem;
  20725. })();
  20726. BABYLON.ParticleSystem = ParticleSystem;
  20727. })(BABYLON || (BABYLON = {}));
  20728. //# sourceMappingURL=babylon.particleSystem.js.map
  20729. var BABYLON;
  20730. (function (BABYLON) {
  20731. var Animation = (function () {
  20732. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  20733. this.name = name;
  20734. this.targetProperty = targetProperty;
  20735. this.framePerSecond = framePerSecond;
  20736. this.dataType = dataType;
  20737. this.loopMode = loopMode;
  20738. this._offsetsCache = {};
  20739. this._highLimitsCache = {};
  20740. this._stopped = false;
  20741. this.targetPropertyPath = targetProperty.split(".");
  20742. this.dataType = dataType;
  20743. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  20744. }
  20745. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  20746. var dataType = undefined;
  20747. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  20748. dataType = Animation.ANIMATIONTYPE_FLOAT;
  20749. }
  20750. else if (from instanceof BABYLON.Quaternion) {
  20751. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  20752. }
  20753. else if (from instanceof BABYLON.Vector3) {
  20754. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  20755. }
  20756. else if (from instanceof BABYLON.Vector2) {
  20757. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  20758. }
  20759. else if (from instanceof BABYLON.Color3) {
  20760. dataType = Animation.ANIMATIONTYPE_COLOR3;
  20761. }
  20762. if (dataType == undefined) {
  20763. return null;
  20764. }
  20765. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  20766. var keys = [];
  20767. keys.push({ frame: 0, value: from });
  20768. keys.push({ frame: totalFrame, value: to });
  20769. animation.setKeys(keys);
  20770. mesh.animations.push(animation);
  20771. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  20772. };
  20773. // Methods
  20774. Animation.prototype.isStopped = function () {
  20775. return this._stopped;
  20776. };
  20777. Animation.prototype.getKeys = function () {
  20778. return this._keys;
  20779. };
  20780. Animation.prototype.getEasingFunction = function () {
  20781. return this._easingFunction;
  20782. };
  20783. Animation.prototype.setEasingFunction = function (easingFunction) {
  20784. this._easingFunction = easingFunction;
  20785. };
  20786. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  20787. return startValue + (endValue - startValue) * gradient;
  20788. };
  20789. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  20790. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  20791. };
  20792. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  20793. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  20794. };
  20795. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  20796. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  20797. };
  20798. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  20799. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  20800. };
  20801. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  20802. var startScale = new BABYLON.Vector3(0, 0, 0);
  20803. var startRotation = new BABYLON.Quaternion();
  20804. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  20805. startValue.decompose(startScale, startRotation, startTranslation);
  20806. var endScale = new BABYLON.Vector3(0, 0, 0);
  20807. var endRotation = new BABYLON.Quaternion();
  20808. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  20809. endValue.decompose(endScale, endRotation, endTranslation);
  20810. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  20811. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  20812. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  20813. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  20814. return result;
  20815. };
  20816. Animation.prototype.clone = function () {
  20817. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  20818. clone.setKeys(this._keys);
  20819. return clone;
  20820. };
  20821. Animation.prototype.setKeys = function (values) {
  20822. this._keys = values.slice(0);
  20823. this._offsetsCache = {};
  20824. this._highLimitsCache = {};
  20825. };
  20826. Animation.prototype._getKeyValue = function (value) {
  20827. if (typeof value === "function") {
  20828. return value();
  20829. }
  20830. return value;
  20831. };
  20832. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  20833. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  20834. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  20835. }
  20836. this.currentFrame = currentFrame;
  20837. // Try to get a hash to find the right key
  20838. 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));
  20839. if (this._keys[startKey].frame >= currentFrame) {
  20840. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  20841. startKey--;
  20842. }
  20843. }
  20844. for (var key = startKey; key < this._keys.length; key++) {
  20845. if (this._keys[key + 1].frame >= currentFrame) {
  20846. var startValue = this._getKeyValue(this._keys[key].value);
  20847. var endValue = this._getKeyValue(this._keys[key + 1].value);
  20848. // gradient : percent of currentFrame between the frame inf and the frame sup
  20849. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  20850. // check for easingFunction and correction of gradient
  20851. if (this._easingFunction != null) {
  20852. gradient = this._easingFunction.ease(gradient);
  20853. }
  20854. switch (this.dataType) {
  20855. // Float
  20856. case Animation.ANIMATIONTYPE_FLOAT:
  20857. switch (loopMode) {
  20858. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20859. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20860. return this.floatInterpolateFunction(startValue, endValue, gradient);
  20861. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20862. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  20863. }
  20864. break;
  20865. // Quaternion
  20866. case Animation.ANIMATIONTYPE_QUATERNION:
  20867. var quaternion = null;
  20868. switch (loopMode) {
  20869. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20870. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20871. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  20872. break;
  20873. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20874. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20875. break;
  20876. }
  20877. return quaternion;
  20878. // Vector3
  20879. case Animation.ANIMATIONTYPE_VECTOR3:
  20880. switch (loopMode) {
  20881. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20882. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20883. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  20884. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20885. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20886. }
  20887. // Vector2
  20888. case Animation.ANIMATIONTYPE_VECTOR2:
  20889. switch (loopMode) {
  20890. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20891. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20892. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  20893. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20894. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20895. }
  20896. // Color3
  20897. case Animation.ANIMATIONTYPE_COLOR3:
  20898. switch (loopMode) {
  20899. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20900. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20901. return this.color3InterpolateFunction(startValue, endValue, gradient);
  20902. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20903. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20904. }
  20905. // Matrix
  20906. case Animation.ANIMATIONTYPE_MATRIX:
  20907. switch (loopMode) {
  20908. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20909. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20910. // return this.matrixInterpolateFunction(startValue, endValue, gradient);
  20911. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20912. return startValue;
  20913. }
  20914. default:
  20915. break;
  20916. }
  20917. break;
  20918. }
  20919. }
  20920. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  20921. };
  20922. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  20923. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  20924. this._stopped = true;
  20925. return false;
  20926. }
  20927. var returnValue = true;
  20928. // Adding a start key at frame 0 if missing
  20929. if (this._keys[0].frame !== 0) {
  20930. var newKey = { frame: 0, value: this._keys[0].value };
  20931. this._keys.splice(0, 0, newKey);
  20932. }
  20933. // Check limits
  20934. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  20935. from = this._keys[0].frame;
  20936. }
  20937. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  20938. to = this._keys[this._keys.length - 1].frame;
  20939. }
  20940. // Compute ratio
  20941. var range = to - from;
  20942. var offsetValue;
  20943. // ratio represents the frame delta between from and to
  20944. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  20945. var highLimitValue = 0;
  20946. if (ratio > range && !loop) {
  20947. returnValue = false;
  20948. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  20949. }
  20950. else {
  20951. // Get max value if required
  20952. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  20953. var keyOffset = to.toString() + from.toString();
  20954. if (!this._offsetsCache[keyOffset]) {
  20955. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20956. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20957. switch (this.dataType) {
  20958. // Float
  20959. case Animation.ANIMATIONTYPE_FLOAT:
  20960. this._offsetsCache[keyOffset] = toValue - fromValue;
  20961. break;
  20962. // Quaternion
  20963. case Animation.ANIMATIONTYPE_QUATERNION:
  20964. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20965. break;
  20966. // Vector3
  20967. case Animation.ANIMATIONTYPE_VECTOR3:
  20968. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20969. // Vector2
  20970. case Animation.ANIMATIONTYPE_VECTOR2:
  20971. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20972. // Color3
  20973. case Animation.ANIMATIONTYPE_COLOR3:
  20974. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20975. default:
  20976. break;
  20977. }
  20978. this._highLimitsCache[keyOffset] = toValue;
  20979. }
  20980. highLimitValue = this._highLimitsCache[keyOffset];
  20981. offsetValue = this._offsetsCache[keyOffset];
  20982. }
  20983. }
  20984. if (offsetValue === undefined) {
  20985. switch (this.dataType) {
  20986. // Float
  20987. case Animation.ANIMATIONTYPE_FLOAT:
  20988. offsetValue = 0;
  20989. break;
  20990. // Quaternion
  20991. case Animation.ANIMATIONTYPE_QUATERNION:
  20992. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  20993. break;
  20994. // Vector3
  20995. case Animation.ANIMATIONTYPE_VECTOR3:
  20996. offsetValue = BABYLON.Vector3.Zero();
  20997. break;
  20998. // Vector2
  20999. case Animation.ANIMATIONTYPE_VECTOR2:
  21000. offsetValue = BABYLON.Vector2.Zero();
  21001. break;
  21002. // Color3
  21003. case Animation.ANIMATIONTYPE_COLOR3:
  21004. offsetValue = BABYLON.Color3.Black();
  21005. }
  21006. }
  21007. // Compute value
  21008. var repeatCount = (ratio / range) >> 0;
  21009. var currentFrame = returnValue ? from + ratio % range : to;
  21010. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21011. // Set value
  21012. if (this.targetPropertyPath.length > 1) {
  21013. var property = this._target[this.targetPropertyPath[0]];
  21014. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21015. property = property[this.targetPropertyPath[index]];
  21016. }
  21017. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21018. }
  21019. else {
  21020. this._target[this.targetPropertyPath[0]] = currentValue;
  21021. }
  21022. if (this._target.markAsDirty) {
  21023. this._target.markAsDirty(this.targetProperty);
  21024. }
  21025. if (!returnValue) {
  21026. this._stopped = true;
  21027. }
  21028. return returnValue;
  21029. };
  21030. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21031. get: function () {
  21032. return Animation._ANIMATIONTYPE_FLOAT;
  21033. },
  21034. enumerable: true,
  21035. configurable: true
  21036. });
  21037. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21038. get: function () {
  21039. return Animation._ANIMATIONTYPE_VECTOR3;
  21040. },
  21041. enumerable: true,
  21042. configurable: true
  21043. });
  21044. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21045. get: function () {
  21046. return Animation._ANIMATIONTYPE_VECTOR2;
  21047. },
  21048. enumerable: true,
  21049. configurable: true
  21050. });
  21051. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21052. get: function () {
  21053. return Animation._ANIMATIONTYPE_QUATERNION;
  21054. },
  21055. enumerable: true,
  21056. configurable: true
  21057. });
  21058. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21059. get: function () {
  21060. return Animation._ANIMATIONTYPE_MATRIX;
  21061. },
  21062. enumerable: true,
  21063. configurable: true
  21064. });
  21065. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21066. get: function () {
  21067. return Animation._ANIMATIONTYPE_COLOR3;
  21068. },
  21069. enumerable: true,
  21070. configurable: true
  21071. });
  21072. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21073. get: function () {
  21074. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21075. },
  21076. enumerable: true,
  21077. configurable: true
  21078. });
  21079. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21080. get: function () {
  21081. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21082. },
  21083. enumerable: true,
  21084. configurable: true
  21085. });
  21086. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21087. get: function () {
  21088. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21089. },
  21090. enumerable: true,
  21091. configurable: true
  21092. });
  21093. // Statics
  21094. Animation._ANIMATIONTYPE_FLOAT = 0;
  21095. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21096. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21097. Animation._ANIMATIONTYPE_MATRIX = 3;
  21098. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21099. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21100. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21101. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21102. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21103. return Animation;
  21104. })();
  21105. BABYLON.Animation = Animation;
  21106. })(BABYLON || (BABYLON = {}));
  21107. //# sourceMappingURL=babylon.animation.js.map
  21108. var BABYLON;
  21109. (function (BABYLON) {
  21110. var Animatable = (function () {
  21111. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21112. if (fromFrame === void 0) { fromFrame = 0; }
  21113. if (toFrame === void 0) { toFrame = 100; }
  21114. if (loopAnimation === void 0) { loopAnimation = false; }
  21115. if (speedRatio === void 0) { speedRatio = 1.0; }
  21116. this.target = target;
  21117. this.fromFrame = fromFrame;
  21118. this.toFrame = toFrame;
  21119. this.loopAnimation = loopAnimation;
  21120. this.speedRatio = speedRatio;
  21121. this.onAnimationEnd = onAnimationEnd;
  21122. this._animations = new Array();
  21123. this._paused = false;
  21124. this.animationStarted = false;
  21125. if (animations) {
  21126. this.appendAnimations(target, animations);
  21127. }
  21128. this._scene = scene;
  21129. scene._activeAnimatables.push(this);
  21130. }
  21131. // Methods
  21132. Animatable.prototype.appendAnimations = function (target, animations) {
  21133. for (var index = 0; index < animations.length; index++) {
  21134. var animation = animations[index];
  21135. animation._target = target;
  21136. this._animations.push(animation);
  21137. }
  21138. };
  21139. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21140. var animations = this._animations;
  21141. for (var index = 0; index < animations.length; index++) {
  21142. if (animations[index].targetProperty === property) {
  21143. return animations[index];
  21144. }
  21145. }
  21146. return null;
  21147. };
  21148. Animatable.prototype.pause = function () {
  21149. if (this._paused) {
  21150. return;
  21151. }
  21152. this._paused = true;
  21153. };
  21154. Animatable.prototype.restart = function () {
  21155. this._paused = false;
  21156. };
  21157. Animatable.prototype.stop = function () {
  21158. var index = this._scene._activeAnimatables.indexOf(this);
  21159. if (index > -1) {
  21160. this._scene._activeAnimatables.splice(index, 1);
  21161. }
  21162. if (this.onAnimationEnd) {
  21163. this.onAnimationEnd();
  21164. }
  21165. };
  21166. Animatable.prototype._animate = function (delay) {
  21167. if (this._paused) {
  21168. if (!this._pausedDelay) {
  21169. this._pausedDelay = delay;
  21170. }
  21171. return true;
  21172. }
  21173. if (!this._localDelayOffset) {
  21174. this._localDelayOffset = delay;
  21175. }
  21176. else if (this._pausedDelay) {
  21177. this._localDelayOffset += delay - this._pausedDelay;
  21178. this._pausedDelay = null;
  21179. }
  21180. // Animating
  21181. var running = false;
  21182. var animations = this._animations;
  21183. for (var index = 0; index < animations.length; index++) {
  21184. var animation = animations[index];
  21185. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21186. running = running || isRunning;
  21187. }
  21188. if (!running) {
  21189. // Remove from active animatables
  21190. index = this._scene._activeAnimatables.indexOf(this);
  21191. this._scene._activeAnimatables.splice(index, 1);
  21192. }
  21193. if (!running && this.onAnimationEnd) {
  21194. this.onAnimationEnd();
  21195. }
  21196. return running;
  21197. };
  21198. return Animatable;
  21199. })();
  21200. BABYLON.Animatable = Animatable;
  21201. })(BABYLON || (BABYLON = {}));
  21202. //# sourceMappingURL=babylon.animatable.js.map
  21203. var __extends = this.__extends || function (d, b) {
  21204. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21205. function __() { this.constructor = d; }
  21206. __.prototype = b.prototype;
  21207. d.prototype = new __();
  21208. };
  21209. var BABYLON;
  21210. (function (BABYLON) {
  21211. var EasingFunction = (function () {
  21212. function EasingFunction() {
  21213. // Properties
  21214. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21215. }
  21216. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21217. get: function () {
  21218. return EasingFunction._EASINGMODE_EASEIN;
  21219. },
  21220. enumerable: true,
  21221. configurable: true
  21222. });
  21223. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21224. get: function () {
  21225. return EasingFunction._EASINGMODE_EASEOUT;
  21226. },
  21227. enumerable: true,
  21228. configurable: true
  21229. });
  21230. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21231. get: function () {
  21232. return EasingFunction._EASINGMODE_EASEINOUT;
  21233. },
  21234. enumerable: true,
  21235. configurable: true
  21236. });
  21237. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21238. var n = Math.min(Math.max(easingMode, 0), 2);
  21239. this._easingMode = n;
  21240. };
  21241. EasingFunction.prototype.getEasingMode = function () {
  21242. return this._easingMode;
  21243. };
  21244. EasingFunction.prototype.easeInCore = function (gradient) {
  21245. throw new Error('You must implement this method');
  21246. };
  21247. EasingFunction.prototype.ease = function (gradient) {
  21248. switch (this._easingMode) {
  21249. case EasingFunction.EASINGMODE_EASEIN:
  21250. return this.easeInCore(gradient);
  21251. case EasingFunction.EASINGMODE_EASEOUT:
  21252. return (1 - this.easeInCore(1 - gradient));
  21253. }
  21254. if (gradient >= 0.5) {
  21255. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21256. }
  21257. return (this.easeInCore(gradient * 2) * 0.5);
  21258. };
  21259. //Statics
  21260. EasingFunction._EASINGMODE_EASEIN = 0;
  21261. EasingFunction._EASINGMODE_EASEOUT = 1;
  21262. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21263. return EasingFunction;
  21264. })();
  21265. BABYLON.EasingFunction = EasingFunction;
  21266. var CircleEase = (function (_super) {
  21267. __extends(CircleEase, _super);
  21268. function CircleEase() {
  21269. _super.apply(this, arguments);
  21270. }
  21271. CircleEase.prototype.easeInCore = function (gradient) {
  21272. gradient = Math.max(0, Math.min(1, gradient));
  21273. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21274. };
  21275. return CircleEase;
  21276. })(EasingFunction);
  21277. BABYLON.CircleEase = CircleEase;
  21278. var BackEase = (function (_super) {
  21279. __extends(BackEase, _super);
  21280. function BackEase(amplitude) {
  21281. if (amplitude === void 0) { amplitude = 1; }
  21282. _super.call(this);
  21283. this.amplitude = amplitude;
  21284. }
  21285. BackEase.prototype.easeInCore = function (gradient) {
  21286. var num = Math.max(0, this.amplitude);
  21287. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21288. };
  21289. return BackEase;
  21290. })(EasingFunction);
  21291. BABYLON.BackEase = BackEase;
  21292. var BounceEase = (function (_super) {
  21293. __extends(BounceEase, _super);
  21294. function BounceEase(bounces, bounciness) {
  21295. if (bounces === void 0) { bounces = 3; }
  21296. if (bounciness === void 0) { bounciness = 2; }
  21297. _super.call(this);
  21298. this.bounces = bounces;
  21299. this.bounciness = bounciness;
  21300. }
  21301. BounceEase.prototype.easeInCore = function (gradient) {
  21302. var y = Math.max(0.0, this.bounces);
  21303. var bounciness = this.bounciness;
  21304. if (bounciness <= 1.0) {
  21305. bounciness = 1.001;
  21306. }
  21307. var num9 = Math.pow(bounciness, y);
  21308. var num5 = 1.0 - bounciness;
  21309. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21310. var num15 = gradient * num4;
  21311. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21312. var num3 = Math.floor(num65);
  21313. var num13 = num3 + 1.0;
  21314. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21315. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21316. var num7 = (num8 + num12) * 0.5;
  21317. var num6 = gradient - num7;
  21318. var num2 = num7 - num8;
  21319. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21320. };
  21321. return BounceEase;
  21322. })(EasingFunction);
  21323. BABYLON.BounceEase = BounceEase;
  21324. var CubicEase = (function (_super) {
  21325. __extends(CubicEase, _super);
  21326. function CubicEase() {
  21327. _super.apply(this, arguments);
  21328. }
  21329. CubicEase.prototype.easeInCore = function (gradient) {
  21330. return (gradient * gradient * gradient);
  21331. };
  21332. return CubicEase;
  21333. })(EasingFunction);
  21334. BABYLON.CubicEase = CubicEase;
  21335. var ElasticEase = (function (_super) {
  21336. __extends(ElasticEase, _super);
  21337. function ElasticEase(oscillations, springiness) {
  21338. if (oscillations === void 0) { oscillations = 3; }
  21339. if (springiness === void 0) { springiness = 3; }
  21340. _super.call(this);
  21341. this.oscillations = oscillations;
  21342. this.springiness = springiness;
  21343. }
  21344. ElasticEase.prototype.easeInCore = function (gradient) {
  21345. var num2;
  21346. var num3 = Math.max(0.0, this.oscillations);
  21347. var num = Math.max(0.0, this.springiness);
  21348. if (num == 0) {
  21349. num2 = gradient;
  21350. }
  21351. else {
  21352. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21353. }
  21354. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21355. };
  21356. return ElasticEase;
  21357. })(EasingFunction);
  21358. BABYLON.ElasticEase = ElasticEase;
  21359. var ExponentialEase = (function (_super) {
  21360. __extends(ExponentialEase, _super);
  21361. function ExponentialEase(exponent) {
  21362. if (exponent === void 0) { exponent = 2; }
  21363. _super.call(this);
  21364. this.exponent = exponent;
  21365. }
  21366. ExponentialEase.prototype.easeInCore = function (gradient) {
  21367. if (this.exponent <= 0) {
  21368. return gradient;
  21369. }
  21370. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21371. };
  21372. return ExponentialEase;
  21373. })(EasingFunction);
  21374. BABYLON.ExponentialEase = ExponentialEase;
  21375. var PowerEase = (function (_super) {
  21376. __extends(PowerEase, _super);
  21377. function PowerEase(power) {
  21378. if (power === void 0) { power = 2; }
  21379. _super.call(this);
  21380. this.power = power;
  21381. }
  21382. PowerEase.prototype.easeInCore = function (gradient) {
  21383. var y = Math.max(0.0, this.power);
  21384. return Math.pow(gradient, y);
  21385. };
  21386. return PowerEase;
  21387. })(EasingFunction);
  21388. BABYLON.PowerEase = PowerEase;
  21389. var QuadraticEase = (function (_super) {
  21390. __extends(QuadraticEase, _super);
  21391. function QuadraticEase() {
  21392. _super.apply(this, arguments);
  21393. }
  21394. QuadraticEase.prototype.easeInCore = function (gradient) {
  21395. return (gradient * gradient);
  21396. };
  21397. return QuadraticEase;
  21398. })(EasingFunction);
  21399. BABYLON.QuadraticEase = QuadraticEase;
  21400. var QuarticEase = (function (_super) {
  21401. __extends(QuarticEase, _super);
  21402. function QuarticEase() {
  21403. _super.apply(this, arguments);
  21404. }
  21405. QuarticEase.prototype.easeInCore = function (gradient) {
  21406. return (gradient * gradient * gradient * gradient);
  21407. };
  21408. return QuarticEase;
  21409. })(EasingFunction);
  21410. BABYLON.QuarticEase = QuarticEase;
  21411. var QuinticEase = (function (_super) {
  21412. __extends(QuinticEase, _super);
  21413. function QuinticEase() {
  21414. _super.apply(this, arguments);
  21415. }
  21416. QuinticEase.prototype.easeInCore = function (gradient) {
  21417. return (gradient * gradient * gradient * gradient * gradient);
  21418. };
  21419. return QuinticEase;
  21420. })(EasingFunction);
  21421. BABYLON.QuinticEase = QuinticEase;
  21422. var SineEase = (function (_super) {
  21423. __extends(SineEase, _super);
  21424. function SineEase() {
  21425. _super.apply(this, arguments);
  21426. }
  21427. SineEase.prototype.easeInCore = function (gradient) {
  21428. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  21429. };
  21430. return SineEase;
  21431. })(EasingFunction);
  21432. BABYLON.SineEase = SineEase;
  21433. var BezierCurveEase = (function (_super) {
  21434. __extends(BezierCurveEase, _super);
  21435. function BezierCurveEase(x1, y1, x2, y2) {
  21436. if (x1 === void 0) { x1 = 0; }
  21437. if (y1 === void 0) { y1 = 0; }
  21438. if (x2 === void 0) { x2 = 1; }
  21439. if (y2 === void 0) { y2 = 1; }
  21440. _super.call(this);
  21441. this.x1 = x1;
  21442. this.y1 = y1;
  21443. this.x2 = x2;
  21444. this.y2 = y2;
  21445. }
  21446. BezierCurveEase.prototype.easeInCore = function (gradient) {
  21447. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  21448. };
  21449. return BezierCurveEase;
  21450. })(EasingFunction);
  21451. BABYLON.BezierCurveEase = BezierCurveEase;
  21452. })(BABYLON || (BABYLON = {}));
  21453. //# sourceMappingURL=babylon.easing.js.map
  21454. var BABYLON;
  21455. (function (BABYLON) {
  21456. var Octree = (function () {
  21457. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  21458. if (maxDepth === void 0) { maxDepth = 2; }
  21459. this.maxDepth = maxDepth;
  21460. this.dynamicContent = new Array();
  21461. this._maxBlockCapacity = maxBlockCapacity || 64;
  21462. this._selectionContent = new BABYLON.SmartArray(1024);
  21463. this._creationFunc = creationFunc;
  21464. }
  21465. // Methods
  21466. Octree.prototype.update = function (worldMin, worldMax, entries) {
  21467. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  21468. };
  21469. Octree.prototype.addMesh = function (entry) {
  21470. for (var index = 0; index < this.blocks.length; index++) {
  21471. var block = this.blocks[index];
  21472. block.addEntry(entry);
  21473. }
  21474. };
  21475. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  21476. this._selectionContent.reset();
  21477. for (var index = 0; index < this.blocks.length; index++) {
  21478. var block = this.blocks[index];
  21479. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  21480. }
  21481. if (allowDuplicate) {
  21482. this._selectionContent.concat(this.dynamicContent);
  21483. }
  21484. else {
  21485. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21486. }
  21487. return this._selectionContent;
  21488. };
  21489. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  21490. this._selectionContent.reset();
  21491. for (var index = 0; index < this.blocks.length; index++) {
  21492. var block = this.blocks[index];
  21493. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  21494. }
  21495. if (allowDuplicate) {
  21496. this._selectionContent.concat(this.dynamicContent);
  21497. }
  21498. else {
  21499. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21500. }
  21501. return this._selectionContent;
  21502. };
  21503. Octree.prototype.intersectsRay = function (ray) {
  21504. this._selectionContent.reset();
  21505. for (var index = 0; index < this.blocks.length; index++) {
  21506. var block = this.blocks[index];
  21507. block.intersectsRay(ray, this._selectionContent);
  21508. }
  21509. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21510. return this._selectionContent;
  21511. };
  21512. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  21513. target.blocks = new Array();
  21514. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  21515. // Segmenting space
  21516. for (var x = 0; x < 2; x++) {
  21517. for (var y = 0; y < 2; y++) {
  21518. for (var z = 0; z < 2; z++) {
  21519. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  21520. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  21521. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  21522. block.addEntries(entries);
  21523. target.blocks.push(block);
  21524. }
  21525. }
  21526. }
  21527. };
  21528. Octree.CreationFuncForMeshes = function (entry, block) {
  21529. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21530. block.entries.push(entry);
  21531. }
  21532. };
  21533. Octree.CreationFuncForSubMeshes = function (entry, block) {
  21534. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21535. block.entries.push(entry);
  21536. }
  21537. };
  21538. return Octree;
  21539. })();
  21540. BABYLON.Octree = Octree;
  21541. })(BABYLON || (BABYLON = {}));
  21542. //# sourceMappingURL=babylon.octree.js.map
  21543. var BABYLON;
  21544. (function (BABYLON) {
  21545. var OctreeBlock = (function () {
  21546. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  21547. this.entries = new Array();
  21548. this._boundingVectors = new Array();
  21549. this._capacity = capacity;
  21550. this._depth = depth;
  21551. this._maxDepth = maxDepth;
  21552. this._creationFunc = creationFunc;
  21553. this._minPoint = minPoint;
  21554. this._maxPoint = maxPoint;
  21555. this._boundingVectors.push(minPoint.clone());
  21556. this._boundingVectors.push(maxPoint.clone());
  21557. this._boundingVectors.push(minPoint.clone());
  21558. this._boundingVectors[2].x = maxPoint.x;
  21559. this._boundingVectors.push(minPoint.clone());
  21560. this._boundingVectors[3].y = maxPoint.y;
  21561. this._boundingVectors.push(minPoint.clone());
  21562. this._boundingVectors[4].z = maxPoint.z;
  21563. this._boundingVectors.push(maxPoint.clone());
  21564. this._boundingVectors[5].z = minPoint.z;
  21565. this._boundingVectors.push(maxPoint.clone());
  21566. this._boundingVectors[6].x = minPoint.x;
  21567. this._boundingVectors.push(maxPoint.clone());
  21568. this._boundingVectors[7].y = minPoint.y;
  21569. }
  21570. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  21571. // Property
  21572. get: function () {
  21573. return this._capacity;
  21574. },
  21575. enumerable: true,
  21576. configurable: true
  21577. });
  21578. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  21579. get: function () {
  21580. return this._minPoint;
  21581. },
  21582. enumerable: true,
  21583. configurable: true
  21584. });
  21585. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  21586. get: function () {
  21587. return this._maxPoint;
  21588. },
  21589. enumerable: true,
  21590. configurable: true
  21591. });
  21592. // Methods
  21593. OctreeBlock.prototype.addEntry = function (entry) {
  21594. if (this.blocks) {
  21595. for (var index = 0; index < this.blocks.length; index++) {
  21596. var block = this.blocks[index];
  21597. block.addEntry(entry);
  21598. }
  21599. return;
  21600. }
  21601. this._creationFunc(entry, this);
  21602. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  21603. this.createInnerBlocks();
  21604. }
  21605. };
  21606. OctreeBlock.prototype.addEntries = function (entries) {
  21607. for (var index = 0; index < entries.length; index++) {
  21608. var mesh = entries[index];
  21609. this.addEntry(mesh);
  21610. }
  21611. };
  21612. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  21613. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  21614. if (this.blocks) {
  21615. for (var index = 0; index < this.blocks.length; index++) {
  21616. var block = this.blocks[index];
  21617. block.select(frustumPlanes, selection, allowDuplicate);
  21618. }
  21619. return;
  21620. }
  21621. if (allowDuplicate) {
  21622. selection.concat(this.entries);
  21623. }
  21624. else {
  21625. selection.concatWithNoDuplicate(this.entries);
  21626. }
  21627. }
  21628. };
  21629. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  21630. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  21631. if (this.blocks) {
  21632. for (var index = 0; index < this.blocks.length; index++) {
  21633. var block = this.blocks[index];
  21634. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  21635. }
  21636. return;
  21637. }
  21638. if (allowDuplicate) {
  21639. selection.concat(this.entries);
  21640. }
  21641. else {
  21642. selection.concatWithNoDuplicate(this.entries);
  21643. }
  21644. }
  21645. };
  21646. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  21647. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  21648. if (this.blocks) {
  21649. for (var index = 0; index < this.blocks.length; index++) {
  21650. var block = this.blocks[index];
  21651. block.intersectsRay(ray, selection);
  21652. }
  21653. return;
  21654. }
  21655. selection.concatWithNoDuplicate(this.entries);
  21656. }
  21657. };
  21658. OctreeBlock.prototype.createInnerBlocks = function () {
  21659. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  21660. };
  21661. return OctreeBlock;
  21662. })();
  21663. BABYLON.OctreeBlock = OctreeBlock;
  21664. })(BABYLON || (BABYLON = {}));
  21665. //# sourceMappingURL=babylon.octreeBlock.js.map
  21666. var BABYLON;
  21667. (function (BABYLON) {
  21668. var Bone = (function () {
  21669. function Bone(name, skeleton, parentBone, matrix) {
  21670. this.name = name;
  21671. this.children = new Array();
  21672. this.animations = new Array();
  21673. this._worldTransform = new BABYLON.Matrix();
  21674. this._absoluteTransform = new BABYLON.Matrix();
  21675. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  21676. this._skeleton = skeleton;
  21677. this._matrix = matrix;
  21678. this._baseMatrix = matrix;
  21679. skeleton.bones.push(this);
  21680. if (parentBone) {
  21681. this._parent = parentBone;
  21682. parentBone.children.push(this);
  21683. }
  21684. else {
  21685. this._parent = null;
  21686. }
  21687. this._updateDifferenceMatrix();
  21688. }
  21689. // Members
  21690. Bone.prototype.getParent = function () {
  21691. return this._parent;
  21692. };
  21693. Bone.prototype.getLocalMatrix = function () {
  21694. return this._matrix;
  21695. };
  21696. Bone.prototype.getBaseMatrix = function () {
  21697. return this._baseMatrix;
  21698. };
  21699. Bone.prototype.getWorldMatrix = function () {
  21700. return this._worldTransform;
  21701. };
  21702. Bone.prototype.getInvertedAbsoluteTransform = function () {
  21703. return this._invertedAbsoluteTransform;
  21704. };
  21705. Bone.prototype.getAbsoluteMatrix = function () {
  21706. var matrix = this._matrix.clone();
  21707. var parent = this._parent;
  21708. while (parent) {
  21709. matrix = matrix.multiply(parent.getLocalMatrix());
  21710. parent = parent.getParent();
  21711. }
  21712. return matrix;
  21713. };
  21714. // Methods
  21715. Bone.prototype.updateMatrix = function (matrix) {
  21716. this._matrix = matrix;
  21717. this._skeleton._markAsDirty();
  21718. this._updateDifferenceMatrix();
  21719. };
  21720. Bone.prototype._updateDifferenceMatrix = function () {
  21721. if (this._parent) {
  21722. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  21723. }
  21724. else {
  21725. this._absoluteTransform.copyFrom(this._matrix);
  21726. }
  21727. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  21728. for (var index = 0; index < this.children.length; index++) {
  21729. this.children[index]._updateDifferenceMatrix();
  21730. }
  21731. };
  21732. Bone.prototype.markAsDirty = function () {
  21733. this._skeleton._markAsDirty();
  21734. };
  21735. return Bone;
  21736. })();
  21737. BABYLON.Bone = Bone;
  21738. })(BABYLON || (BABYLON = {}));
  21739. //# sourceMappingURL=babylon.bone.js.map
  21740. var BABYLON;
  21741. (function (BABYLON) {
  21742. var Skeleton = (function () {
  21743. function Skeleton(name, id, scene) {
  21744. this.name = name;
  21745. this.id = id;
  21746. this.bones = new Array();
  21747. this._isDirty = true;
  21748. this._identity = BABYLON.Matrix.Identity();
  21749. this.bones = [];
  21750. this._scene = scene;
  21751. scene.skeletons.push(this);
  21752. this.prepare();
  21753. //make sure it will recalculate the matrix next time prepare is called.
  21754. this._isDirty = true;
  21755. }
  21756. // Members
  21757. Skeleton.prototype.getTransformMatrices = function () {
  21758. return this._transformMatrices;
  21759. };
  21760. // Methods
  21761. Skeleton.prototype._markAsDirty = function () {
  21762. this._isDirty = true;
  21763. };
  21764. Skeleton.prototype.prepare = function () {
  21765. if (!this._isDirty) {
  21766. return;
  21767. }
  21768. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  21769. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  21770. }
  21771. for (var index = 0; index < this.bones.length; index++) {
  21772. var bone = this.bones[index];
  21773. var parentBone = bone.getParent();
  21774. if (parentBone) {
  21775. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  21776. }
  21777. else {
  21778. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  21779. }
  21780. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  21781. }
  21782. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  21783. this._isDirty = false;
  21784. this._scene._activeBones += this.bones.length;
  21785. };
  21786. Skeleton.prototype.getAnimatables = function () {
  21787. if (!this._animatables || this._animatables.length !== this.bones.length) {
  21788. this._animatables = [];
  21789. for (var index = 0; index < this.bones.length; index++) {
  21790. this._animatables.push(this.bones[index]);
  21791. }
  21792. }
  21793. return this._animatables;
  21794. };
  21795. Skeleton.prototype.clone = function (name, id) {
  21796. var result = new Skeleton(name, id || name, this._scene);
  21797. for (var index = 0; index < this.bones.length; index++) {
  21798. var source = this.bones[index];
  21799. var parentBone = null;
  21800. if (source.getParent()) {
  21801. var parentIndex = this.bones.indexOf(source.getParent());
  21802. parentBone = result.bones[parentIndex];
  21803. }
  21804. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  21805. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  21806. }
  21807. return result;
  21808. };
  21809. return Skeleton;
  21810. })();
  21811. BABYLON.Skeleton = Skeleton;
  21812. })(BABYLON || (BABYLON = {}));
  21813. //# sourceMappingURL=babylon.skeleton.js.map
  21814. var BABYLON;
  21815. (function (BABYLON) {
  21816. var PostProcess = (function () {
  21817. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  21818. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  21819. this.name = name;
  21820. this.width = -1;
  21821. this.height = -1;
  21822. this._reusable = false;
  21823. this._textures = new BABYLON.SmartArray(2);
  21824. this._currentRenderTextureInd = 0;
  21825. if (camera != null) {
  21826. this._camera = camera;
  21827. this._scene = camera.getScene();
  21828. camera.attachPostProcess(this);
  21829. this._engine = this._scene.getEngine();
  21830. }
  21831. else {
  21832. this._engine = engine;
  21833. }
  21834. this._renderRatio = ratio;
  21835. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  21836. this._reusable = reusable || false;
  21837. samplers = samplers || [];
  21838. samplers.push("textureSampler");
  21839. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  21840. }
  21841. PostProcess.prototype.isReusable = function () {
  21842. return this._reusable;
  21843. };
  21844. PostProcess.prototype.activate = function (camera, sourceTexture) {
  21845. camera = camera || this._camera;
  21846. var scene = camera.getScene();
  21847. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  21848. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  21849. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  21850. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  21851. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  21852. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  21853. if (this._textures.length > 0) {
  21854. for (var i = 0; i < this._textures.length; i++) {
  21855. this._engine._releaseTexture(this._textures.data[i]);
  21856. }
  21857. this._textures.reset();
  21858. }
  21859. this.width = desiredWidth;
  21860. this.height = desiredHeight;
  21861. 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 }));
  21862. if (this._reusable) {
  21863. 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 }));
  21864. }
  21865. if (this.onSizeChanged) {
  21866. this.onSizeChanged();
  21867. }
  21868. }
  21869. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  21870. if (this.onActivate) {
  21871. this.onActivate(camera);
  21872. }
  21873. // Clear
  21874. if (this.clearColor) {
  21875. this._engine.clear(this.clearColor, true, true);
  21876. }
  21877. else {
  21878. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  21879. }
  21880. if (this._reusable) {
  21881. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  21882. }
  21883. };
  21884. PostProcess.prototype.apply = function () {
  21885. // Check
  21886. if (!this._effect.isReady())
  21887. return null;
  21888. // States
  21889. this._engine.enableEffect(this._effect);
  21890. this._engine.setState(false);
  21891. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21892. this._engine.setDepthBuffer(false);
  21893. this._engine.setDepthWrite(false);
  21894. // Texture
  21895. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  21896. // Parameters
  21897. if (this.onApply) {
  21898. this.onApply(this._effect);
  21899. }
  21900. return this._effect;
  21901. };
  21902. PostProcess.prototype.dispose = function (camera) {
  21903. camera = camera || this._camera;
  21904. if (this._textures.length > 0) {
  21905. for (var i = 0; i < this._textures.length; i++) {
  21906. this._engine._releaseTexture(this._textures.data[i]);
  21907. }
  21908. this._textures.reset();
  21909. }
  21910. if (!camera) {
  21911. return;
  21912. }
  21913. camera.detachPostProcess(this);
  21914. var index = camera._postProcesses.indexOf(this);
  21915. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  21916. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  21917. }
  21918. };
  21919. return PostProcess;
  21920. })();
  21921. BABYLON.PostProcess = PostProcess;
  21922. })(BABYLON || (BABYLON = {}));
  21923. //# sourceMappingURL=babylon.postProcess.js.map
  21924. var BABYLON;
  21925. (function (BABYLON) {
  21926. var PostProcessManager = (function () {
  21927. function PostProcessManager(scene) {
  21928. this._vertexDeclaration = [2];
  21929. this._vertexStrideSize = 2 * 4;
  21930. this._scene = scene;
  21931. }
  21932. PostProcessManager.prototype._prepareBuffers = function () {
  21933. if (this._vertexBuffer) {
  21934. return;
  21935. }
  21936. // VBO
  21937. var vertices = [];
  21938. vertices.push(1, 1);
  21939. vertices.push(-1, 1);
  21940. vertices.push(-1, -1);
  21941. vertices.push(1, -1);
  21942. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  21943. // Indices
  21944. var indices = [];
  21945. indices.push(0);
  21946. indices.push(1);
  21947. indices.push(2);
  21948. indices.push(0);
  21949. indices.push(2);
  21950. indices.push(3);
  21951. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  21952. };
  21953. // Methods
  21954. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  21955. var postProcesses = this._scene.activeCamera._postProcesses;
  21956. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21957. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21958. return false;
  21959. }
  21960. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  21961. return true;
  21962. };
  21963. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  21964. var engine = this._scene.getEngine();
  21965. for (var index = 0; index < postProcesses.length; index++) {
  21966. if (index < postProcesses.length - 1) {
  21967. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  21968. }
  21969. else {
  21970. if (targetTexture) {
  21971. engine.bindFramebuffer(targetTexture);
  21972. }
  21973. else {
  21974. engine.restoreDefaultFramebuffer();
  21975. }
  21976. }
  21977. var pp = postProcesses[index];
  21978. var effect = pp.apply();
  21979. if (effect) {
  21980. if (pp.onBeforeRender) {
  21981. pp.onBeforeRender(effect);
  21982. }
  21983. // VBOs
  21984. this._prepareBuffers();
  21985. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21986. // Draw order
  21987. engine.draw(true, 0, 6);
  21988. }
  21989. }
  21990. // Restore depth buffer
  21991. engine.setDepthBuffer(true);
  21992. engine.setDepthWrite(true);
  21993. };
  21994. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  21995. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  21996. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21997. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21998. return;
  21999. }
  22000. var engine = this._scene.getEngine();
  22001. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22002. if (index < postProcessesTakenIndices.length - 1) {
  22003. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22004. }
  22005. else {
  22006. if (targetTexture) {
  22007. engine.bindFramebuffer(targetTexture);
  22008. }
  22009. else {
  22010. engine.restoreDefaultFramebuffer();
  22011. }
  22012. }
  22013. if (doNotPresent) {
  22014. break;
  22015. }
  22016. var pp = postProcesses[postProcessesTakenIndices[index]];
  22017. var effect = pp.apply();
  22018. if (effect) {
  22019. if (pp.onBeforeRender) {
  22020. pp.onBeforeRender(effect);
  22021. }
  22022. // VBOs
  22023. this._prepareBuffers();
  22024. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22025. // Draw order
  22026. engine.draw(true, 0, 6);
  22027. }
  22028. }
  22029. // Restore depth buffer
  22030. engine.setDepthBuffer(true);
  22031. engine.setDepthWrite(true);
  22032. };
  22033. PostProcessManager.prototype.dispose = function () {
  22034. if (this._vertexBuffer) {
  22035. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22036. this._vertexBuffer = null;
  22037. }
  22038. if (this._indexBuffer) {
  22039. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22040. this._indexBuffer = null;
  22041. }
  22042. };
  22043. return PostProcessManager;
  22044. })();
  22045. BABYLON.PostProcessManager = PostProcessManager;
  22046. })(BABYLON || (BABYLON = {}));
  22047. //# sourceMappingURL=babylon.postProcessManager.js.map
  22048. var __extends = this.__extends || function (d, b) {
  22049. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22050. function __() { this.constructor = d; }
  22051. __.prototype = b.prototype;
  22052. d.prototype = new __();
  22053. };
  22054. var BABYLON;
  22055. (function (BABYLON) {
  22056. var PassPostProcess = (function (_super) {
  22057. __extends(PassPostProcess, _super);
  22058. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22059. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22060. }
  22061. return PassPostProcess;
  22062. })(BABYLON.PostProcess);
  22063. BABYLON.PassPostProcess = PassPostProcess;
  22064. })(BABYLON || (BABYLON = {}));
  22065. //# sourceMappingURL=babylon.passPostProcess.js.map
  22066. var __extends = this.__extends || function (d, b) {
  22067. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22068. function __() { this.constructor = d; }
  22069. __.prototype = b.prototype;
  22070. d.prototype = new __();
  22071. };
  22072. var BABYLON;
  22073. (function (BABYLON) {
  22074. var BlurPostProcess = (function (_super) {
  22075. __extends(BlurPostProcess, _super);
  22076. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  22077. var _this = this;
  22078. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  22079. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  22080. this.direction = direction;
  22081. this.blurWidth = blurWidth;
  22082. this.onApply = function (effect) {
  22083. effect.setFloat2("screenSize", _this.width, _this.height);
  22084. effect.setVector2("direction", _this.direction);
  22085. effect.setFloat("blurWidth", _this.blurWidth);
  22086. };
  22087. }
  22088. return BlurPostProcess;
  22089. })(BABYLON.PostProcess);
  22090. BABYLON.BlurPostProcess = BlurPostProcess;
  22091. })(BABYLON || (BABYLON = {}));
  22092. //# sourceMappingURL=babylon.blurPostProcess.js.map
  22093. var __extends = this.__extends || function (d, b) {
  22094. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22095. function __() { this.constructor = d; }
  22096. __.prototype = b.prototype;
  22097. d.prototype = new __();
  22098. };
  22099. var BABYLON;
  22100. (function (BABYLON) {
  22101. var RefractionPostProcess = (function (_super) {
  22102. __extends(RefractionPostProcess, _super);
  22103. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  22104. var _this = this;
  22105. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  22106. this.color = color;
  22107. this.depth = depth;
  22108. this.colorLevel = colorLevel;
  22109. this.onActivate = function (cam) {
  22110. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  22111. };
  22112. this.onApply = function (effect) {
  22113. effect.setColor3("baseColor", _this.color);
  22114. effect.setFloat("depth", _this.depth);
  22115. effect.setFloat("colorLevel", _this.colorLevel);
  22116. effect.setTexture("refractionSampler", _this._refRexture);
  22117. };
  22118. }
  22119. // Methods
  22120. RefractionPostProcess.prototype.dispose = function (camera) {
  22121. if (this._refRexture) {
  22122. this._refRexture.dispose();
  22123. }
  22124. _super.prototype.dispose.call(this, camera);
  22125. };
  22126. return RefractionPostProcess;
  22127. })(BABYLON.PostProcess);
  22128. BABYLON.RefractionPostProcess = RefractionPostProcess;
  22129. })(BABYLON || (BABYLON = {}));
  22130. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  22131. var __extends = this.__extends || function (d, b) {
  22132. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22133. function __() { this.constructor = d; }
  22134. __.prototype = b.prototype;
  22135. d.prototype = new __();
  22136. };
  22137. var BABYLON;
  22138. (function (BABYLON) {
  22139. var BlackAndWhitePostProcess = (function (_super) {
  22140. __extends(BlackAndWhitePostProcess, _super);
  22141. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22142. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  22143. }
  22144. return BlackAndWhitePostProcess;
  22145. })(BABYLON.PostProcess);
  22146. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  22147. })(BABYLON || (BABYLON = {}));
  22148. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  22149. var __extends = this.__extends || function (d, b) {
  22150. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22151. function __() { this.constructor = d; }
  22152. __.prototype = b.prototype;
  22153. d.prototype = new __();
  22154. };
  22155. var BABYLON;
  22156. (function (BABYLON) {
  22157. var ConvolutionPostProcess = (function (_super) {
  22158. __extends(ConvolutionPostProcess, _super);
  22159. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  22160. var _this = this;
  22161. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  22162. this.kernel = kernel;
  22163. this.onApply = function (effect) {
  22164. effect.setFloat2("screenSize", _this.width, _this.height);
  22165. effect.setArray("kernel", _this.kernel);
  22166. };
  22167. }
  22168. // Statics
  22169. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  22170. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  22171. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  22172. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  22173. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  22174. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  22175. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  22176. return ConvolutionPostProcess;
  22177. })(BABYLON.PostProcess);
  22178. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  22179. })(BABYLON || (BABYLON = {}));
  22180. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  22181. var __extends = this.__extends || function (d, b) {
  22182. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22183. function __() { this.constructor = d; }
  22184. __.prototype = b.prototype;
  22185. d.prototype = new __();
  22186. };
  22187. var BABYLON;
  22188. (function (BABYLON) {
  22189. var FilterPostProcess = (function (_super) {
  22190. __extends(FilterPostProcess, _super);
  22191. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  22192. var _this = this;
  22193. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  22194. this.kernelMatrix = kernelMatrix;
  22195. this.onApply = function (effect) {
  22196. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  22197. };
  22198. }
  22199. return FilterPostProcess;
  22200. })(BABYLON.PostProcess);
  22201. BABYLON.FilterPostProcess = FilterPostProcess;
  22202. })(BABYLON || (BABYLON = {}));
  22203. //# sourceMappingURL=babylon.filterPostProcess.js.map
  22204. var __extends = this.__extends || function (d, b) {
  22205. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22206. function __() { this.constructor = d; }
  22207. __.prototype = b.prototype;
  22208. d.prototype = new __();
  22209. };
  22210. var BABYLON;
  22211. (function (BABYLON) {
  22212. var FxaaPostProcess = (function (_super) {
  22213. __extends(FxaaPostProcess, _super);
  22214. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22215. var _this = this;
  22216. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  22217. this.onSizeChanged = function () {
  22218. _this.texelWidth = 1.0 / _this.width;
  22219. _this.texelHeight = 1.0 / _this.height;
  22220. };
  22221. this.onApply = function (effect) {
  22222. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  22223. };
  22224. }
  22225. return FxaaPostProcess;
  22226. })(BABYLON.PostProcess);
  22227. BABYLON.FxaaPostProcess = FxaaPostProcess;
  22228. })(BABYLON || (BABYLON = {}));
  22229. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  22230. var __extends = this.__extends || function (d, b) {
  22231. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  22232. function __() { this.constructor = d; }
  22233. __.prototype = b.prototype;
  22234. d.prototype = new __();
  22235. };
  22236. var BABYLON;
  22237. (function (BABYLON) {
  22238. var StereogramInterlacePostProcess = (function (_super) {
  22239. __extends(StereogramInterlacePostProcess, _super);
  22240. function StereogramInterlacePostProcess(name, camB, postProcessA, isStereogramHoriz, samplingMode) {
  22241. var _this = this;
  22242. _super.call(this, name, "stereogramInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereogramHoriz ? "#define IS_STEREOGRAM_HORIZ 1" : undefined);
  22243. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  22244. this.onSizeChanged = function () {
  22245. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  22246. };
  22247. this.onApply = function (effect) {
  22248. effect.setTextureFromPostProcess("camASampler", postProcessA);
  22249. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  22250. };
  22251. }
  22252. return StereogramInterlacePostProcess;
  22253. })(BABYLON.PostProcess);
  22254. BABYLON.StereogramInterlacePostProcess = StereogramInterlacePostProcess;
  22255. })(BABYLON || (BABYLON = {}));
  22256. //# sourceMappingURL=babylon.stereogramInterlacePostProcess.js.map
  22257. var BABYLON;
  22258. (function (BABYLON) {
  22259. var LensFlare = (function () {
  22260. function LensFlare(size, position, color, imgUrl, system) {
  22261. this.size = size;
  22262. this.position = position;
  22263. this.dispose = function () {
  22264. if (this.texture) {
  22265. this.texture.dispose();
  22266. }
  22267. // Remove from scene
  22268. var index = this._system.lensFlares.indexOf(this);
  22269. this._system.lensFlares.splice(index, 1);
  22270. };
  22271. this.color = color || new BABYLON.Color3(1, 1, 1);
  22272. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  22273. this._system = system;
  22274. system.lensFlares.push(this);
  22275. }
  22276. return LensFlare;
  22277. })();
  22278. BABYLON.LensFlare = LensFlare;
  22279. })(BABYLON || (BABYLON = {}));
  22280. //# sourceMappingURL=babylon.lensFlare.js.map
  22281. var BABYLON;
  22282. (function (BABYLON) {
  22283. var LensFlareSystem = (function () {
  22284. function LensFlareSystem(name, emitter, scene) {
  22285. this.name = name;
  22286. this.lensFlares = new Array();
  22287. this.borderLimit = 300;
  22288. this._vertexDeclaration = [2];
  22289. this._vertexStrideSize = 2 * 4;
  22290. this._isEnabled = true;
  22291. this._scene = scene;
  22292. this._emitter = emitter;
  22293. scene.lensFlareSystems.push(this);
  22294. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  22295. // VBO
  22296. var vertices = [];
  22297. vertices.push(1, 1);
  22298. vertices.push(-1, 1);
  22299. vertices.push(-1, -1);
  22300. vertices.push(1, -1);
  22301. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  22302. // Indices
  22303. var indices = [];
  22304. indices.push(0);
  22305. indices.push(1);
  22306. indices.push(2);
  22307. indices.push(0);
  22308. indices.push(2);
  22309. indices.push(3);
  22310. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22311. // Effects
  22312. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  22313. }
  22314. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  22315. get: function () {
  22316. return this._isEnabled;
  22317. },
  22318. set: function (value) {
  22319. this._isEnabled = value;
  22320. },
  22321. enumerable: true,
  22322. configurable: true
  22323. });
  22324. LensFlareSystem.prototype.getScene = function () {
  22325. return this._scene;
  22326. };
  22327. LensFlareSystem.prototype.getEmitter = function () {
  22328. return this._emitter;
  22329. };
  22330. LensFlareSystem.prototype.getEmitterPosition = function () {
  22331. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  22332. };
  22333. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  22334. var position = this.getEmitterPosition();
  22335. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  22336. this._positionX = position.x;
  22337. this._positionY = position.y;
  22338. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  22339. if (position.z > 0) {
  22340. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  22341. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  22342. return true;
  22343. }
  22344. }
  22345. return false;
  22346. };
  22347. LensFlareSystem.prototype._isVisible = function () {
  22348. if (!this._isEnabled) {
  22349. return false;
  22350. }
  22351. var emitterPosition = this.getEmitterPosition();
  22352. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  22353. var distance = direction.length();
  22354. direction.normalize();
  22355. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  22356. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  22357. return !pickInfo.hit || pickInfo.distance > distance;
  22358. };
  22359. LensFlareSystem.prototype.render = function () {
  22360. if (!this._effect.isReady())
  22361. return false;
  22362. var engine = this._scene.getEngine();
  22363. var viewport = this._scene.activeCamera.viewport;
  22364. var globalViewport = viewport.toGlobal(engine);
  22365. // Position
  22366. if (!this.computeEffectivePosition(globalViewport)) {
  22367. return false;
  22368. }
  22369. // Visibility
  22370. if (!this._isVisible()) {
  22371. return false;
  22372. }
  22373. // Intensity
  22374. var awayX;
  22375. var awayY;
  22376. if (this._positionX < this.borderLimit + globalViewport.x) {
  22377. awayX = this.borderLimit + globalViewport.x - this._positionX;
  22378. }
  22379. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  22380. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  22381. }
  22382. else {
  22383. awayX = 0;
  22384. }
  22385. if (this._positionY < this.borderLimit + globalViewport.y) {
  22386. awayY = this.borderLimit + globalViewport.y - this._positionY;
  22387. }
  22388. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  22389. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  22390. }
  22391. else {
  22392. awayY = 0;
  22393. }
  22394. var away = (awayX > awayY) ? awayX : awayY;
  22395. if (away > this.borderLimit) {
  22396. away = this.borderLimit;
  22397. }
  22398. var intensity = 1.0 - (away / this.borderLimit);
  22399. if (intensity < 0) {
  22400. return false;
  22401. }
  22402. if (intensity > 1.0) {
  22403. intensity = 1.0;
  22404. }
  22405. // Position
  22406. var centerX = globalViewport.x + globalViewport.width / 2;
  22407. var centerY = globalViewport.y + globalViewport.height / 2;
  22408. var distX = centerX - this._positionX;
  22409. var distY = centerY - this._positionY;
  22410. // Effects
  22411. engine.enableEffect(this._effect);
  22412. engine.setState(false);
  22413. engine.setDepthBuffer(false);
  22414. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  22415. // VBOs
  22416. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  22417. // Flares
  22418. for (var index = 0; index < this.lensFlares.length; index++) {
  22419. var flare = this.lensFlares[index];
  22420. var x = centerX - (distX * flare.position);
  22421. var y = centerY - (distY * flare.position);
  22422. var cw = flare.size;
  22423. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  22424. var cx = 2 * (x / globalViewport.width) - 1.0;
  22425. var cy = 1.0 - 2 * (y / globalViewport.height);
  22426. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  22427. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  22428. // Texture
  22429. this._effect.setTexture("textureSampler", flare.texture);
  22430. // Color
  22431. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  22432. // Draw order
  22433. engine.draw(true, 0, 6);
  22434. }
  22435. engine.setDepthBuffer(true);
  22436. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22437. return true;
  22438. };
  22439. LensFlareSystem.prototype.dispose = function () {
  22440. if (this._vertexBuffer) {
  22441. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22442. this._vertexBuffer = null;
  22443. }
  22444. if (this._indexBuffer) {
  22445. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22446. this._indexBuffer = null;
  22447. }
  22448. while (this.lensFlares.length) {
  22449. this.lensFlares[0].dispose();
  22450. }
  22451. // Remove from scene
  22452. var index = this._scene.lensFlareSystems.indexOf(this);
  22453. this._scene.lensFlareSystems.splice(index, 1);
  22454. };
  22455. return LensFlareSystem;
  22456. })();
  22457. BABYLON.LensFlareSystem = LensFlareSystem;
  22458. })(BABYLON || (BABYLON = {}));
  22459. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  22460. var BABYLON;
  22461. (function (BABYLON) {
  22462. var CannonJSPlugin = (function () {
  22463. function CannonJSPlugin() {
  22464. this._registeredMeshes = [];
  22465. this._physicsMaterials = [];
  22466. this.updateBodyPosition = function (mesh) {
  22467. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22468. var registeredMesh = this._registeredMeshes[index];
  22469. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22470. var body = registeredMesh.body;
  22471. var center = mesh.getBoundingInfo().boundingBox.center;
  22472. body.position.set(center.x, center.z, center.y);
  22473. body.quaternion.x = mesh.rotationQuaternion.x;
  22474. body.quaternion.z = mesh.rotationQuaternion.y;
  22475. body.quaternion.y = mesh.rotationQuaternion.z;
  22476. body.quaternion.w = -mesh.rotationQuaternion.w;
  22477. return;
  22478. }
  22479. }
  22480. };
  22481. }
  22482. CannonJSPlugin.prototype.initialize = function (iterations) {
  22483. if (iterations === void 0) { iterations = 10; }
  22484. this._world = new CANNON.World();
  22485. this._world.broadphase = new CANNON.NaiveBroadphase();
  22486. this._world.solver.iterations = iterations;
  22487. };
  22488. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22489. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22490. };
  22491. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22492. this._world.step(delta);
  22493. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22494. var registeredMesh = this._registeredMeshes[index];
  22495. if (registeredMesh.isChild) {
  22496. continue;
  22497. }
  22498. // Body position
  22499. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22500. var deltaPos = registeredMesh.delta;
  22501. if (deltaPos) {
  22502. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22503. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22504. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22505. }
  22506. else {
  22507. registeredMesh.mesh.position.x = bodyX;
  22508. registeredMesh.mesh.position.y = bodyZ;
  22509. registeredMesh.mesh.position.z = bodyY;
  22510. }
  22511. if (!registeredMesh.mesh.rotationQuaternion) {
  22512. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22513. }
  22514. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22515. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22516. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22517. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22518. }
  22519. };
  22520. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22521. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22522. };
  22523. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22524. this.unregisterMesh(mesh);
  22525. mesh.computeWorldMatrix(true);
  22526. switch (impostor) {
  22527. case BABYLON.PhysicsEngine.SphereImpostor:
  22528. var bbox = mesh.getBoundingInfo().boundingBox;
  22529. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22530. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22531. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22532. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22533. case BABYLON.PhysicsEngine.BoxImpostor:
  22534. bbox = mesh.getBoundingInfo().boundingBox;
  22535. var min = bbox.minimumWorld;
  22536. var max = bbox.maximumWorld;
  22537. var box = max.subtract(min).scale(0.5);
  22538. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22539. case BABYLON.PhysicsEngine.PlaneImpostor:
  22540. return this._createPlane(mesh, options);
  22541. case BABYLON.PhysicsEngine.MeshImpostor:
  22542. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22543. var rawFaces = mesh.getIndices();
  22544. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22545. }
  22546. return null;
  22547. };
  22548. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22549. var shape = new CANNON.Sphere(radius);
  22550. if (!options) {
  22551. return shape;
  22552. }
  22553. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22554. };
  22555. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22556. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22557. if (!options) {
  22558. return shape;
  22559. }
  22560. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22561. };
  22562. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22563. var shape = new CANNON.Plane();
  22564. if (!options) {
  22565. return shape;
  22566. }
  22567. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22568. };
  22569. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22570. var verts = [], faces = [];
  22571. mesh.computeWorldMatrix(true);
  22572. // Get vertices
  22573. for (var i = 0; i < rawVerts.length; i += 3) {
  22574. var transformed = BABYLON.Vector3.Zero();
  22575. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22576. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22577. }
  22578. // Get faces
  22579. for (var j = 0; j < rawFaces.length; j += 3) {
  22580. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22581. }
  22582. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22583. if (!options) {
  22584. return shape;
  22585. }
  22586. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22587. };
  22588. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22589. var index;
  22590. var mat;
  22591. for (index = 0; index < this._physicsMaterials.length; index++) {
  22592. mat = this._physicsMaterials[index];
  22593. if (mat.friction === friction && mat.restitution === restitution) {
  22594. return mat;
  22595. }
  22596. }
  22597. var currentMat = new CANNON.Material();
  22598. currentMat.friction = friction;
  22599. currentMat.restitution = restitution;
  22600. this._physicsMaterials.push(currentMat);
  22601. for (index = 0; index < this._physicsMaterials.length; index++) {
  22602. mat = this._physicsMaterials[index];
  22603. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22604. contactMaterial.contactEquationStiffness = 1e10;
  22605. contactMaterial.contactEquationRegularizationTime = 10;
  22606. this._world.addContactMaterial(contactMaterial);
  22607. }
  22608. return currentMat;
  22609. };
  22610. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22611. var initialRotation = null;
  22612. if (mesh.rotationQuaternion) {
  22613. initialRotation = mesh.rotationQuaternion.clone();
  22614. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22615. }
  22616. // The delta between the mesh position and the mesh bounding box center
  22617. var bbox = mesh.getBoundingInfo().boundingBox;
  22618. var deltaPosition = mesh.position.subtract(bbox.center);
  22619. var material = this._addMaterial(friction, restitution);
  22620. var body = new CANNON.RigidBody(mass, shape, material);
  22621. if (initialRotation) {
  22622. body.quaternion.x = initialRotation.x;
  22623. body.quaternion.z = initialRotation.y;
  22624. body.quaternion.y = initialRotation.z;
  22625. body.quaternion.w = -initialRotation.w;
  22626. }
  22627. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22628. this._world.add(body);
  22629. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22630. return body;
  22631. };
  22632. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22633. var compoundShape = new CANNON.Compound();
  22634. for (var index = 0; index < parts.length; index++) {
  22635. var mesh = parts[index].mesh;
  22636. var shape = this.registerMesh(mesh, parts[index].impostor);
  22637. if (index == 0) {
  22638. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22639. }
  22640. else {
  22641. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22642. }
  22643. }
  22644. var initialMesh = parts[0].mesh;
  22645. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22646. body.parts = parts;
  22647. return body;
  22648. };
  22649. CannonJSPlugin.prototype._unbindBody = function (body) {
  22650. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22651. var registeredMesh = this._registeredMeshes[index];
  22652. if (registeredMesh.body === body) {
  22653. registeredMesh.body = null;
  22654. registeredMesh.delta = 0;
  22655. }
  22656. }
  22657. };
  22658. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22659. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22660. var registeredMesh = this._registeredMeshes[index];
  22661. if (registeredMesh.mesh === mesh) {
  22662. // Remove body
  22663. if (registeredMesh.body) {
  22664. this._world.remove(registeredMesh.body);
  22665. this._unbindBody(registeredMesh.body);
  22666. }
  22667. this._registeredMeshes.splice(index, 1);
  22668. return;
  22669. }
  22670. }
  22671. };
  22672. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22673. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22674. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22675. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22676. var registeredMesh = this._registeredMeshes[index];
  22677. if (registeredMesh.mesh === mesh) {
  22678. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22679. return;
  22680. }
  22681. }
  22682. };
  22683. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22684. var body1 = null, body2 = null;
  22685. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22686. var registeredMesh = this._registeredMeshes[index];
  22687. if (registeredMesh.mesh === mesh1) {
  22688. body1 = registeredMesh.body;
  22689. }
  22690. else if (registeredMesh.mesh === mesh2) {
  22691. body2 = registeredMesh.body;
  22692. }
  22693. }
  22694. if (!body1 || !body2) {
  22695. return false;
  22696. }
  22697. 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));
  22698. this._world.addConstraint(constraint);
  22699. return true;
  22700. };
  22701. CannonJSPlugin.prototype.dispose = function () {
  22702. while (this._registeredMeshes.length) {
  22703. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22704. }
  22705. };
  22706. CannonJSPlugin.prototype.isSupported = function () {
  22707. return window.CANNON !== undefined;
  22708. };
  22709. return CannonJSPlugin;
  22710. })();
  22711. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22712. })(BABYLON || (BABYLON = {}));
  22713. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22714. var BABYLON;
  22715. (function (BABYLON) {
  22716. var OimoJSPlugin = (function () {
  22717. function OimoJSPlugin() {
  22718. this._registeredMeshes = [];
  22719. /**
  22720. * Update the body position according to the mesh position
  22721. * @param mesh
  22722. */
  22723. this.updateBodyPosition = function (mesh) {
  22724. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22725. var registeredMesh = this._registeredMeshes[index];
  22726. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22727. var body = registeredMesh.body.body;
  22728. mesh.computeWorldMatrix(true);
  22729. var center = mesh.getBoundingInfo().boundingBox.center;
  22730. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  22731. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  22732. body.sleeping = false;
  22733. return;
  22734. }
  22735. // Case where the parent has been updated
  22736. if (registeredMesh.mesh.parent === mesh) {
  22737. mesh.computeWorldMatrix(true);
  22738. registeredMesh.mesh.computeWorldMatrix(true);
  22739. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  22740. var absoluteRotation = mesh.rotation;
  22741. body = registeredMesh.body.body;
  22742. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  22743. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  22744. body.sleeping = false;
  22745. return;
  22746. }
  22747. }
  22748. };
  22749. }
  22750. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  22751. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22752. };
  22753. OimoJSPlugin.prototype.initialize = function (iterations) {
  22754. this._world = new OIMO.World();
  22755. this._world.clear();
  22756. };
  22757. OimoJSPlugin.prototype.setGravity = function (gravity) {
  22758. this._world.gravity = gravity;
  22759. };
  22760. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22761. var body = null;
  22762. this.unregisterMesh(mesh);
  22763. mesh.computeWorldMatrix(true);
  22764. var initialRotation = null;
  22765. if (mesh.rotationQuaternion) {
  22766. initialRotation = mesh.rotationQuaternion.clone();
  22767. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22768. mesh.computeWorldMatrix(true);
  22769. }
  22770. var bbox = mesh.getBoundingInfo().boundingBox;
  22771. // The delta between the mesh position and the mesh bounding box center
  22772. var deltaPosition = mesh.position.subtract(bbox.center);
  22773. // Transform delta position with the rotation
  22774. if (initialRotation) {
  22775. var m = new BABYLON.Matrix();
  22776. initialRotation.toRotationMatrix(m);
  22777. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  22778. }
  22779. // register mesh
  22780. switch (impostor) {
  22781. case BABYLON.PhysicsEngine.SphereImpostor:
  22782. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22783. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22784. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22785. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22786. body = new OIMO.Body({
  22787. type: 'sphere',
  22788. size: [size],
  22789. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22790. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22791. move: options.mass != 0,
  22792. config: [options.mass, options.friction, options.restitution],
  22793. world: this._world
  22794. });
  22795. break;
  22796. case BABYLON.PhysicsEngine.PlaneImpostor:
  22797. //Oimo "fakes" a cylinder as a box, so why don't we!
  22798. case BABYLON.PhysicsEngine.CylinderImpostor:
  22799. case BABYLON.PhysicsEngine.BoxImpostor:
  22800. var min = bbox.minimumWorld;
  22801. var max = bbox.maximumWorld;
  22802. var box = max.subtract(min);
  22803. var sizeX = this._checkWithEpsilon(box.x);
  22804. var sizeY = this._checkWithEpsilon(box.y);
  22805. var sizeZ = this._checkWithEpsilon(box.z);
  22806. body = new OIMO.Body({
  22807. type: 'box',
  22808. size: [sizeX, sizeY, sizeZ],
  22809. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22810. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22811. move: options.mass != 0,
  22812. config: [options.mass, options.friction, options.restitution],
  22813. world: this._world
  22814. });
  22815. break;
  22816. }
  22817. //If quaternion was set as the rotation of the object
  22818. if (initialRotation) {
  22819. //We have to access the rigid body's properties to set the quaternion.
  22820. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  22821. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  22822. //update the internal rotation matrix
  22823. body.body.syncShapes();
  22824. }
  22825. this._registeredMeshes.push({
  22826. mesh: mesh,
  22827. body: body,
  22828. delta: deltaPosition
  22829. });
  22830. return body;
  22831. };
  22832. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22833. var types = [], sizes = [], positions = [], rotations = [];
  22834. var initialMesh = parts[0].mesh;
  22835. for (var index = 0; index < parts.length; index++) {
  22836. var part = parts[index];
  22837. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  22838. types.push(bodyParameters.type);
  22839. sizes.push.apply(sizes, bodyParameters.size);
  22840. positions.push.apply(positions, bodyParameters.pos);
  22841. rotations.push.apply(rotations, bodyParameters.rot);
  22842. }
  22843. var body = new OIMO.Body({
  22844. type: types,
  22845. size: sizes,
  22846. pos: positions,
  22847. rot: rotations,
  22848. move: options.mass != 0,
  22849. config: [options.mass, options.friction, options.restitution],
  22850. world: this._world
  22851. });
  22852. this._registeredMeshes.push({
  22853. mesh: initialMesh,
  22854. body: body
  22855. });
  22856. return body;
  22857. };
  22858. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  22859. var bodyParameters = null;
  22860. var mesh = part.mesh;
  22861. // We need the bounding box/sphere info to compute the physics body
  22862. mesh.computeWorldMatrix();
  22863. switch (part.impostor) {
  22864. case BABYLON.PhysicsEngine.SphereImpostor:
  22865. var bbox = mesh.getBoundingInfo().boundingBox;
  22866. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22867. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22868. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22869. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22870. bodyParameters = {
  22871. type: 'sphere',
  22872. /* bug with oimo : sphere needs 3 sizes in this case */
  22873. size: [size, -1, -1],
  22874. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  22875. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22876. };
  22877. break;
  22878. case BABYLON.PhysicsEngine.PlaneImpostor:
  22879. case BABYLON.PhysicsEngine.BoxImpostor:
  22880. bbox = mesh.getBoundingInfo().boundingBox;
  22881. var min = bbox.minimumWorld;
  22882. var max = bbox.maximumWorld;
  22883. var box = max.subtract(min);
  22884. var sizeX = this._checkWithEpsilon(box.x);
  22885. var sizeY = this._checkWithEpsilon(box.y);
  22886. var sizeZ = this._checkWithEpsilon(box.z);
  22887. var relativePosition = mesh.position;
  22888. bodyParameters = {
  22889. type: 'box',
  22890. size: [sizeX, sizeY, sizeZ],
  22891. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  22892. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22893. };
  22894. break;
  22895. }
  22896. return bodyParameters;
  22897. };
  22898. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  22899. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22900. var registeredMesh = this._registeredMeshes[index];
  22901. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22902. if (registeredMesh.body) {
  22903. this._world.removeRigidBody(registeredMesh.body.body);
  22904. this._unbindBody(registeredMesh.body);
  22905. }
  22906. this._registeredMeshes.splice(index, 1);
  22907. return;
  22908. }
  22909. }
  22910. };
  22911. OimoJSPlugin.prototype._unbindBody = function (body) {
  22912. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22913. var registeredMesh = this._registeredMeshes[index];
  22914. if (registeredMesh.body === body) {
  22915. registeredMesh.body = null;
  22916. }
  22917. }
  22918. };
  22919. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22920. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22921. var registeredMesh = this._registeredMeshes[index];
  22922. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22923. // Get object mass to have a behaviour similar to cannon.js
  22924. var mass = registeredMesh.body.body.massInfo.mass;
  22925. // The force is scaled with the mass of object
  22926. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  22927. return;
  22928. }
  22929. }
  22930. };
  22931. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22932. var body1 = null, body2 = null;
  22933. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22934. var registeredMesh = this._registeredMeshes[index];
  22935. if (registeredMesh.mesh === mesh1) {
  22936. body1 = registeredMesh.body.body;
  22937. }
  22938. else if (registeredMesh.mesh === mesh2) {
  22939. body2 = registeredMesh.body.body;
  22940. }
  22941. }
  22942. if (!body1 || !body2) {
  22943. return false;
  22944. }
  22945. if (!options) {
  22946. options = {};
  22947. }
  22948. new OIMO.Link({
  22949. type: options.type,
  22950. body1: body1,
  22951. body2: body2,
  22952. min: options.min,
  22953. max: options.max,
  22954. axe1: options.axe1,
  22955. axe2: options.axe2,
  22956. pos1: [pivot1.x, pivot1.y, pivot1.z],
  22957. pos2: [pivot2.x, pivot2.y, pivot2.z],
  22958. collision: options.collision,
  22959. spring: options.spring,
  22960. world: this._world
  22961. });
  22962. return true;
  22963. };
  22964. OimoJSPlugin.prototype.dispose = function () {
  22965. this._world.clear();
  22966. while (this._registeredMeshes.length) {
  22967. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22968. }
  22969. };
  22970. OimoJSPlugin.prototype.isSupported = function () {
  22971. return OIMO !== undefined;
  22972. };
  22973. OimoJSPlugin.prototype._getLastShape = function (body) {
  22974. var lastShape = body.shapes;
  22975. while (lastShape.next) {
  22976. lastShape = lastShape.next;
  22977. }
  22978. return lastShape;
  22979. };
  22980. OimoJSPlugin.prototype.runOneStep = function (time) {
  22981. this._world.step();
  22982. // Update the position of all registered meshes
  22983. var i = this._registeredMeshes.length;
  22984. var m;
  22985. while (i--) {
  22986. var body = this._registeredMeshes[i].body.body;
  22987. var mesh = this._registeredMeshes[i].mesh;
  22988. var delta = this._registeredMeshes[i].delta;
  22989. if (!body.sleeping) {
  22990. if (body.shapes.next) {
  22991. var parentShape = this._getLastShape(body);
  22992. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  22993. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  22994. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  22995. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  22996. if (!mesh.rotationQuaternion) {
  22997. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22998. }
  22999. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  23000. mesh.computeWorldMatrix();
  23001. }
  23002. else {
  23003. m = body.getMatrix();
  23004. mtx = BABYLON.Matrix.FromArray(m);
  23005. // Body position
  23006. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  23007. if (!delta) {
  23008. mesh.position.x = bodyX;
  23009. mesh.position.y = bodyY;
  23010. mesh.position.z = bodyZ;
  23011. }
  23012. else {
  23013. mesh.position.x = bodyX + delta.x;
  23014. mesh.position.y = bodyY + delta.y;
  23015. mesh.position.z = bodyZ + delta.z;
  23016. }
  23017. if (!mesh.rotationQuaternion) {
  23018. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23019. }
  23020. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  23021. mesh.computeWorldMatrix();
  23022. }
  23023. }
  23024. }
  23025. };
  23026. return OimoJSPlugin;
  23027. })();
  23028. BABYLON.OimoJSPlugin = OimoJSPlugin;
  23029. })(BABYLON || (BABYLON = {}));
  23030. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  23031. var BABYLON;
  23032. (function (BABYLON) {
  23033. var PhysicsEngine = (function () {
  23034. function PhysicsEngine(plugin) {
  23035. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23036. }
  23037. PhysicsEngine.prototype._initialize = function (gravity) {
  23038. this._currentPlugin.initialize();
  23039. this._setGravity(gravity);
  23040. };
  23041. PhysicsEngine.prototype._runOneStep = function (delta) {
  23042. if (delta > 0.1) {
  23043. delta = 0.1;
  23044. }
  23045. else if (delta <= 0) {
  23046. delta = 1.0 / 60.0;
  23047. }
  23048. this._currentPlugin.runOneStep(delta);
  23049. };
  23050. PhysicsEngine.prototype._setGravity = function (gravity) {
  23051. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  23052. this._currentPlugin.setGravity(this.gravity);
  23053. };
  23054. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23055. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23056. };
  23057. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23058. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23059. };
  23060. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23061. this._currentPlugin.unregisterMesh(mesh);
  23062. };
  23063. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23064. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23065. };
  23066. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23067. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23068. };
  23069. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23070. this._currentPlugin.updateBodyPosition(mesh);
  23071. };
  23072. PhysicsEngine.prototype.dispose = function () {
  23073. this._currentPlugin.dispose();
  23074. };
  23075. PhysicsEngine.prototype.isSupported = function () {
  23076. return this._currentPlugin.isSupported();
  23077. };
  23078. // Statics
  23079. PhysicsEngine.NoImpostor = 0;
  23080. PhysicsEngine.SphereImpostor = 1;
  23081. PhysicsEngine.BoxImpostor = 2;
  23082. PhysicsEngine.PlaneImpostor = 3;
  23083. PhysicsEngine.MeshImpostor = 4;
  23084. PhysicsEngine.CapsuleImpostor = 5;
  23085. PhysicsEngine.ConeImpostor = 6;
  23086. PhysicsEngine.CylinderImpostor = 7;
  23087. PhysicsEngine.ConvexHullImpostor = 8;
  23088. PhysicsEngine.Epsilon = 0.001;
  23089. return PhysicsEngine;
  23090. })();
  23091. BABYLON.PhysicsEngine = PhysicsEngine;
  23092. })(BABYLON || (BABYLON = {}));
  23093. //# sourceMappingURL=babylon.physicsEngine.js.map
  23094. var BABYLON;
  23095. (function (BABYLON) {
  23096. var serializeLight = function (light) {
  23097. var serializationObject = {};
  23098. serializationObject.name = light.name;
  23099. serializationObject.id = light.id;
  23100. serializationObject.tags = BABYLON.Tags.GetTags(light);
  23101. if (light instanceof BABYLON.PointLight) {
  23102. serializationObject.type = 0;
  23103. serializationObject.position = light.position.asArray();
  23104. }
  23105. else if (light instanceof BABYLON.DirectionalLight) {
  23106. serializationObject.type = 1;
  23107. var directionalLight = light;
  23108. serializationObject.position = directionalLight.position.asArray();
  23109. serializationObject.direction = directionalLight.direction.asArray();
  23110. }
  23111. else if (light instanceof BABYLON.SpotLight) {
  23112. serializationObject.type = 2;
  23113. var spotLight = light;
  23114. serializationObject.position = spotLight.position.asArray();
  23115. serializationObject.direction = spotLight.position.asArray();
  23116. serializationObject.angle = spotLight.angle;
  23117. serializationObject.exponent = spotLight.exponent;
  23118. }
  23119. else if (light instanceof BABYLON.HemisphericLight) {
  23120. serializationObject.type = 3;
  23121. var hemisphericLight = light;
  23122. serializationObject.direction = hemisphericLight.direction.asArray();
  23123. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  23124. }
  23125. if (light.intensity) {
  23126. serializationObject.intensity = light.intensity;
  23127. }
  23128. serializationObject.range = light.range;
  23129. serializationObject.diffuse = light.diffuse.asArray();
  23130. serializationObject.specular = light.specular.asArray();
  23131. return serializationObject;
  23132. };
  23133. var serializeFresnelParameter = function (fresnelParameter) {
  23134. var serializationObject = {};
  23135. serializationObject.isEnabled = fresnelParameter.isEnabled;
  23136. serializationObject.leftColor = fresnelParameter.leftColor;
  23137. serializationObject.rightColor = fresnelParameter.rightColor;
  23138. serializationObject.bias = fresnelParameter.bias;
  23139. serializationObject.power = fresnelParameter.power;
  23140. return serializationObject;
  23141. };
  23142. var appendAnimations = function (source, destination) {
  23143. if (source.animations) {
  23144. destination.animations = [];
  23145. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23146. var animation = source.animations[animationIndex];
  23147. destination.animations.push(serializeAnimation(animation));
  23148. }
  23149. }
  23150. };
  23151. var serializeCamera = function (camera) {
  23152. var serializationObject = {};
  23153. serializationObject.name = camera.name;
  23154. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  23155. serializationObject.id = camera.id;
  23156. serializationObject.position = camera.position.asArray();
  23157. // Parent
  23158. if (camera.parent) {
  23159. serializationObject.parentId = camera.parent.id;
  23160. }
  23161. serializationObject.fov = camera.fov;
  23162. serializationObject.minZ = camera.minZ;
  23163. serializationObject.maxZ = camera.maxZ;
  23164. serializationObject.inertia = camera.inertia;
  23165. //setting the type
  23166. if (camera instanceof BABYLON.FreeCamera) {
  23167. serializationObject.type = "FreeCamera";
  23168. }
  23169. else if (camera instanceof BABYLON.ArcRotateCamera) {
  23170. serializationObject.type = "ArcRotateCamera";
  23171. }
  23172. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23173. serializationObject.type = "AnaglyphArcRotateCamera";
  23174. }
  23175. else if (camera instanceof BABYLON.GamepadCamera) {
  23176. serializationObject.type = "GamepadCamera";
  23177. }
  23178. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  23179. serializationObject.type = "AnaglyphFreeCamera";
  23180. }
  23181. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  23182. serializationObject.type = "DeviceOrientationCamera";
  23183. }
  23184. else if (camera instanceof BABYLON.FollowCamera) {
  23185. serializationObject.type = "FollowCamera";
  23186. }
  23187. else if (camera instanceof BABYLON.TouchCamera) {
  23188. serializationObject.type = "TouchCamera";
  23189. }
  23190. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  23191. serializationObject.type = "VirtualJoysticksCamera";
  23192. }
  23193. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  23194. serializationObject.type = "WebVRFreeCamera";
  23195. }
  23196. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  23197. serializationObject.type = "VRDeviceOrientationFreeCamera";
  23198. }
  23199. //special properties of specific cameras
  23200. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23201. var arcCamera = camera;
  23202. serializationObject.alpha = arcCamera.alpha;
  23203. serializationObject.beta = arcCamera.beta;
  23204. serializationObject.radius = arcCamera.radius;
  23205. if (arcCamera.target && arcCamera.target.id) {
  23206. serializationObject.lockedTargetId = arcCamera.target.id;
  23207. }
  23208. }
  23209. else if (camera instanceof BABYLON.FollowCamera) {
  23210. var followCam = camera;
  23211. serializationObject.radius = followCam.radius;
  23212. serializationObject.heightOffset = followCam.heightOffset;
  23213. serializationObject.rotationOffset = followCam.rotationOffset;
  23214. }
  23215. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23216. //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.
  23217. if (camera['_eyeSpace'] !== undefined) {
  23218. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  23219. }
  23220. }
  23221. //general properties that not all cameras have. The [] is due to typescript's type safety
  23222. if (camera['speed'] !== undefined) {
  23223. serializationObject.speed = camera['speed'];
  23224. }
  23225. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  23226. serializationObject.target = camera['target'].asArray();
  23227. }
  23228. // Target
  23229. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  23230. serializationObject.rotation = camera['rotation'].asArray();
  23231. }
  23232. // Locked target
  23233. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  23234. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  23235. }
  23236. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  23237. serializationObject.applyGravity = camera['applyGravity'] || false;
  23238. if (camera['ellipsoid']) {
  23239. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  23240. }
  23241. // Animations
  23242. appendAnimations(camera, serializationObject);
  23243. // Layer mask
  23244. serializationObject.layerMask = camera.layerMask;
  23245. return serializationObject;
  23246. };
  23247. var serializeAnimation = function (animation) {
  23248. var serializationObject = {};
  23249. serializationObject.name = animation.name;
  23250. serializationObject.property = animation.targetProperty;
  23251. serializationObject.framePerSecond = animation.framePerSecond;
  23252. serializationObject.dataType = animation.dataType;
  23253. serializationObject.loopBehavior = animation.loopMode;
  23254. var dataType = animation.dataType;
  23255. serializationObject.keys = [];
  23256. var keys = animation.getKeys();
  23257. for (var index = 0; index < keys.length; index++) {
  23258. var animationKey = keys[index];
  23259. var key = {};
  23260. key.frame = animationKey.frame;
  23261. switch (dataType) {
  23262. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  23263. key.values = [animationKey.value];
  23264. break;
  23265. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  23266. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  23267. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  23268. key.values = animationKey.value.asArray();
  23269. break;
  23270. }
  23271. serializationObject.keys.push(key);
  23272. }
  23273. return serializationObject;
  23274. };
  23275. var serializeMultiMaterial = function (material) {
  23276. var serializationObject = {};
  23277. serializationObject.name = material.name;
  23278. serializationObject.id = material.id;
  23279. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23280. serializationObject.materials = [];
  23281. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  23282. var subMat = material.subMaterials[matIndex];
  23283. if (subMat) {
  23284. serializationObject.materials.push(subMat.id);
  23285. }
  23286. else {
  23287. serializationObject.materials.push(null);
  23288. }
  23289. }
  23290. return serializationObject;
  23291. };
  23292. var serializeMaterial = function (material) {
  23293. var serializationObject = {};
  23294. serializationObject.name = material.name;
  23295. serializationObject.ambient = material.ambientColor.asArray();
  23296. serializationObject.diffuse = material.diffuseColor.asArray();
  23297. serializationObject.specular = material.specularColor.asArray();
  23298. serializationObject.specularPower = material.specularPower;
  23299. serializationObject.emissive = material.emissiveColor.asArray();
  23300. serializationObject.alpha = material.alpha;
  23301. serializationObject.id = material.id;
  23302. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23303. serializationObject.backFaceCulling = material.backFaceCulling;
  23304. if (material.diffuseTexture) {
  23305. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  23306. }
  23307. if (material.diffuseFresnelParameters) {
  23308. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  23309. }
  23310. if (material.ambientTexture) {
  23311. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  23312. }
  23313. if (material.opacityTexture) {
  23314. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  23315. }
  23316. if (material.opacityFresnelParameters) {
  23317. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  23318. }
  23319. if (material.reflectionTexture) {
  23320. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  23321. }
  23322. if (material.reflectionFresnelParameters) {
  23323. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  23324. }
  23325. if (material.emissiveTexture) {
  23326. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  23327. }
  23328. if (material.emissiveFresnelParameters) {
  23329. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  23330. }
  23331. if (material.specularTexture) {
  23332. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  23333. }
  23334. if (material.bumpTexture) {
  23335. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  23336. }
  23337. return serializationObject;
  23338. };
  23339. var serializeTexture = function (texture) {
  23340. var serializationObject = {};
  23341. if (!texture.name) {
  23342. return null;
  23343. }
  23344. if (texture instanceof BABYLON.CubeTexture) {
  23345. serializationObject.name = texture.name;
  23346. serializationObject.hasAlpha = texture.hasAlpha;
  23347. serializationObject.level = texture.level;
  23348. serializationObject.coordinatesMode = texture.coordinatesMode;
  23349. return serializationObject;
  23350. }
  23351. if (texture instanceof BABYLON.MirrorTexture) {
  23352. var mirrorTexture = texture;
  23353. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  23354. serializationObject.renderList = [];
  23355. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  23356. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  23357. }
  23358. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  23359. }
  23360. else if (texture instanceof BABYLON.RenderTargetTexture) {
  23361. var renderTargetTexture = texture;
  23362. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  23363. serializationObject.renderList = [];
  23364. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  23365. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  23366. }
  23367. }
  23368. var regularTexture = texture;
  23369. serializationObject.name = texture.name;
  23370. serializationObject.hasAlpha = texture.hasAlpha;
  23371. serializationObject.level = texture.level;
  23372. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  23373. serializationObject.coordinatesMode = texture.coordinatesMode;
  23374. serializationObject.uOffset = regularTexture.uOffset;
  23375. serializationObject.vOffset = regularTexture.vOffset;
  23376. serializationObject.uScale = regularTexture.uScale;
  23377. serializationObject.vScale = regularTexture.vScale;
  23378. serializationObject.uAng = regularTexture.uAng;
  23379. serializationObject.vAng = regularTexture.vAng;
  23380. serializationObject.wAng = regularTexture.wAng;
  23381. serializationObject.wrapU = texture.wrapU;
  23382. serializationObject.wrapV = texture.wrapV;
  23383. // Animations
  23384. appendAnimations(texture, serializationObject);
  23385. return serializationObject;
  23386. };
  23387. var serializeSkeleton = function (skeleton) {
  23388. var serializationObject = {};
  23389. serializationObject.name = skeleton.name;
  23390. serializationObject.id = skeleton.id;
  23391. serializationObject.bones = [];
  23392. for (var index = 0; index < skeleton.bones.length; index++) {
  23393. var bone = skeleton.bones[index];
  23394. var serializedBone = {
  23395. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  23396. name: bone.name,
  23397. matrix: bone.getLocalMatrix().toArray()
  23398. };
  23399. serializationObject.bones.push(serializedBone);
  23400. if (bone.animations && bone.animations.length > 0) {
  23401. serializedBone.animation = serializeAnimation(bone.animations[0]);
  23402. }
  23403. }
  23404. return serializationObject;
  23405. };
  23406. var serializeParticleSystem = function (particleSystem) {
  23407. var serializationObject = {};
  23408. serializationObject.emitterId = particleSystem.emitter.id;
  23409. serializationObject.capacity = particleSystem.getCapacity();
  23410. if (particleSystem.particleTexture) {
  23411. serializationObject.textureName = particleSystem.particleTexture.name;
  23412. }
  23413. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  23414. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  23415. serializationObject.minSize = particleSystem.minSize;
  23416. serializationObject.maxSize = particleSystem.maxSize;
  23417. serializationObject.minLifeTime = particleSystem.minLifeTime;
  23418. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  23419. serializationObject.emitRate = particleSystem.emitRate;
  23420. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  23421. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  23422. serializationObject.gravity = particleSystem.gravity.asArray();
  23423. serializationObject.direction1 = particleSystem.direction1.asArray();
  23424. serializationObject.direction2 = particleSystem.direction2.asArray();
  23425. serializationObject.color1 = particleSystem.color1.asArray();
  23426. serializationObject.color2 = particleSystem.color2.asArray();
  23427. serializationObject.colorDead = particleSystem.colorDead.asArray();
  23428. serializationObject.updateSpeed = particleSystem.updateSpeed;
  23429. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  23430. serializationObject.textureMask = particleSystem.textureMask.asArray();
  23431. serializationObject.blendMode = particleSystem.blendMode;
  23432. return serializationObject;
  23433. };
  23434. var serializeLensFlareSystem = function (lensFlareSystem) {
  23435. var serializationObject = {};
  23436. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  23437. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  23438. serializationObject.flares = [];
  23439. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  23440. var flare = lensFlareSystem.lensFlares[index];
  23441. serializationObject.flares.push({
  23442. size: flare.size,
  23443. position: flare.position,
  23444. color: flare.color.asArray(),
  23445. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  23446. });
  23447. }
  23448. return serializationObject;
  23449. };
  23450. var serializeShadowGenerator = function (light) {
  23451. var serializationObject = {};
  23452. var shadowGenerator = light.getShadowGenerator();
  23453. serializationObject.lightId = light.id;
  23454. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  23455. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  23456. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  23457. serializationObject.renderList = [];
  23458. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  23459. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  23460. serializationObject.renderList.push(mesh.id);
  23461. }
  23462. return serializationObject;
  23463. };
  23464. var serializedGeometries = [];
  23465. var serializeGeometry = function (geometry, serializationGeometries) {
  23466. if (serializedGeometries[geometry.id]) {
  23467. return;
  23468. }
  23469. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  23470. serializationGeometries.boxes.push(serializeBox(geometry));
  23471. }
  23472. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  23473. serializationGeometries.spheres.push(serializeSphere(geometry));
  23474. }
  23475. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  23476. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  23477. }
  23478. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  23479. serializationGeometries.toruses.push(serializeTorus(geometry));
  23480. }
  23481. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  23482. serializationGeometries.grounds.push(serializeGround(geometry));
  23483. }
  23484. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  23485. serializationGeometries.planes.push(serializePlane(geometry));
  23486. }
  23487. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  23488. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  23489. }
  23490. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  23491. throw new Error("Unknow primitive type");
  23492. }
  23493. else {
  23494. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  23495. }
  23496. serializedGeometries[geometry.id] = true;
  23497. };
  23498. var serializeGeometryBase = function (geometry) {
  23499. var serializationObject = {};
  23500. serializationObject.id = geometry.id;
  23501. if (BABYLON.Tags.HasTags(geometry)) {
  23502. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  23503. }
  23504. return serializationObject;
  23505. };
  23506. var serializeVertexData = function (vertexData) {
  23507. var serializationObject = serializeGeometryBase(vertexData);
  23508. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23509. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23510. }
  23511. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23512. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23513. }
  23514. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23515. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23516. }
  23517. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23518. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  23519. }
  23520. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23521. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  23522. }
  23523. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23524. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23525. serializationObject.matricesIndices._isExpanded = true;
  23526. }
  23527. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23528. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23529. }
  23530. serializationObject.indices = vertexData.getIndices();
  23531. return serializationObject;
  23532. };
  23533. var serializePrimitive = function (primitive) {
  23534. var serializationObject = serializeGeometryBase(primitive);
  23535. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  23536. return serializationObject;
  23537. };
  23538. var serializeBox = function (box) {
  23539. var serializationObject = serializePrimitive(box);
  23540. serializationObject.size = box.size;
  23541. return serializationObject;
  23542. };
  23543. var serializeSphere = function (sphere) {
  23544. var serializationObject = serializePrimitive(sphere);
  23545. serializationObject.segments = sphere.segments;
  23546. serializationObject.diameter = sphere.diameter;
  23547. return serializationObject;
  23548. };
  23549. var serializeCylinder = function (cylinder) {
  23550. var serializationObject = serializePrimitive(cylinder);
  23551. serializationObject.height = cylinder.height;
  23552. serializationObject.diameterTop = cylinder.diameterTop;
  23553. serializationObject.diameterBottom = cylinder.diameterBottom;
  23554. serializationObject.tessellation = cylinder.tessellation;
  23555. return serializationObject;
  23556. };
  23557. var serializeTorus = function (torus) {
  23558. var serializationObject = serializePrimitive(torus);
  23559. serializationObject.diameter = torus.diameter;
  23560. serializationObject.thickness = torus.thickness;
  23561. serializationObject.tessellation = torus.tessellation;
  23562. return serializationObject;
  23563. };
  23564. var serializeGround = function (ground) {
  23565. var serializationObject = serializePrimitive(ground);
  23566. serializationObject.width = ground.width;
  23567. serializationObject.height = ground.height;
  23568. serializationObject.subdivisions = ground.subdivisions;
  23569. return serializationObject;
  23570. };
  23571. var serializePlane = function (plane) {
  23572. var serializationObject = serializePrimitive(plane);
  23573. serializationObject.size = plane.size;
  23574. return serializationObject;
  23575. };
  23576. var serializeTorusKnot = function (torusKnot) {
  23577. var serializationObject = serializePrimitive(torusKnot);
  23578. serializationObject.radius = torusKnot.radius;
  23579. serializationObject.tube = torusKnot.tube;
  23580. serializationObject.radialSegments = torusKnot.radialSegments;
  23581. serializationObject.tubularSegments = torusKnot.tubularSegments;
  23582. serializationObject.p = torusKnot.p;
  23583. serializationObject.q = torusKnot.q;
  23584. return serializationObject;
  23585. };
  23586. var serializeMesh = function (mesh, serializationScene) {
  23587. var serializationObject = {};
  23588. serializationObject.name = mesh.name;
  23589. serializationObject.id = mesh.id;
  23590. if (BABYLON.Tags.HasTags(mesh)) {
  23591. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  23592. }
  23593. serializationObject.position = mesh.position.asArray();
  23594. if (mesh.rotationQuaternion) {
  23595. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  23596. }
  23597. else if (mesh.rotation) {
  23598. serializationObject.rotation = mesh.rotation.asArray();
  23599. }
  23600. serializationObject.scaling = mesh.scaling.asArray();
  23601. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  23602. serializationObject.isEnabled = mesh.isEnabled();
  23603. serializationObject.isVisible = mesh.isVisible;
  23604. serializationObject.infiniteDistance = mesh.infiniteDistance;
  23605. serializationObject.pickable = mesh.isPickable;
  23606. serializationObject.receiveShadows = mesh.receiveShadows;
  23607. serializationObject.billboardMode = mesh.billboardMode;
  23608. serializationObject.visibility = mesh.visibility;
  23609. serializationObject.checkCollisions = mesh.checkCollisions;
  23610. // Parent
  23611. if (mesh.parent) {
  23612. serializationObject.parentId = mesh.parent.id;
  23613. }
  23614. // Geometry
  23615. var geometry = mesh._geometry;
  23616. if (geometry) {
  23617. var geometryId = geometry.id;
  23618. serializationObject.geometryId = geometryId;
  23619. if (!mesh.getScene().getGeometryByID(geometryId)) {
  23620. // 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
  23621. serializeGeometry(geometry, serializationScene.geometries);
  23622. }
  23623. // SubMeshes
  23624. serializationObject.subMeshes = [];
  23625. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23626. var subMesh = mesh.subMeshes[subIndex];
  23627. serializationObject.subMeshes.push({
  23628. materialIndex: subMesh.materialIndex,
  23629. verticesStart: subMesh.verticesStart,
  23630. verticesCount: subMesh.verticesCount,
  23631. indexStart: subMesh.indexStart,
  23632. indexCount: subMesh.indexCount
  23633. });
  23634. }
  23635. }
  23636. // Material
  23637. if (mesh.material) {
  23638. serializationObject.materialId = mesh.material.id;
  23639. }
  23640. else {
  23641. mesh.material = null;
  23642. }
  23643. // Skeleton
  23644. if (mesh.skeleton) {
  23645. serializationObject.skeletonId = mesh.skeleton.id;
  23646. }
  23647. // Physics
  23648. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  23649. serializationObject.physicsMass = mesh.getPhysicsMass();
  23650. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  23651. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  23652. switch (mesh.getPhysicsImpostor()) {
  23653. case BABYLON.PhysicsEngine.BoxImpostor:
  23654. serializationObject.physicsImpostor = 1;
  23655. break;
  23656. case BABYLON.PhysicsEngine.SphereImpostor:
  23657. serializationObject.physicsImpostor = 2;
  23658. break;
  23659. }
  23660. }
  23661. // Instances
  23662. serializationObject.instances = [];
  23663. for (var index = 0; index < mesh.instances.length; index++) {
  23664. var instance = mesh.instances[index];
  23665. var serializationInstance = {
  23666. name: instance.name,
  23667. position: instance.position,
  23668. rotation: instance.rotation,
  23669. rotationQuaternion: instance.rotationQuaternion,
  23670. scaling: instance.scaling
  23671. };
  23672. serializationObject.instances.push(serializationInstance);
  23673. // Animations
  23674. appendAnimations(instance, serializationInstance);
  23675. }
  23676. // Animations
  23677. appendAnimations(mesh, serializationObject);
  23678. // Layer mask
  23679. serializationObject.layerMask = mesh.layerMask;
  23680. return serializationObject;
  23681. };
  23682. var SceneSerializer = (function () {
  23683. function SceneSerializer() {
  23684. }
  23685. SceneSerializer.Serialize = function (scene) {
  23686. var serializationObject = {};
  23687. // Scene
  23688. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  23689. serializationObject.autoClear = scene.autoClear;
  23690. serializationObject.clearColor = scene.clearColor.asArray();
  23691. serializationObject.ambientColor = scene.ambientColor.asArray();
  23692. serializationObject.gravity = scene.gravity.asArray();
  23693. // Fog
  23694. if (scene.fogMode && scene.fogMode !== 0) {
  23695. serializationObject.fogMode = scene.fogMode;
  23696. serializationObject.fogColor = scene.fogColor.asArray();
  23697. serializationObject.fogStart = scene.fogStart;
  23698. serializationObject.fogEnd = scene.fogEnd;
  23699. serializationObject.fogDensity = scene.fogDensity;
  23700. }
  23701. // Lights
  23702. serializationObject.lights = [];
  23703. for (var index = 0; index < scene.lights.length; index++) {
  23704. var light = scene.lights[index];
  23705. serializationObject.lights.push(serializeLight(light));
  23706. }
  23707. // Cameras
  23708. serializationObject.cameras = [];
  23709. for (index = 0; index < scene.cameras.length; index++) {
  23710. var camera = scene.cameras[index];
  23711. serializationObject.cameras.push(serializeCamera(camera));
  23712. }
  23713. if (scene.activeCamera) {
  23714. serializationObject.activeCameraID = scene.activeCamera.id;
  23715. }
  23716. // Materials
  23717. serializationObject.materials = [];
  23718. serializationObject.multiMaterials = [];
  23719. for (index = 0; index < scene.materials.length; index++) {
  23720. var material = scene.materials[index];
  23721. if (material instanceof BABYLON.StandardMaterial) {
  23722. serializationObject.materials.push(serializeMaterial(material));
  23723. }
  23724. else if (material instanceof BABYLON.MultiMaterial) {
  23725. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  23726. }
  23727. }
  23728. // Skeletons
  23729. serializationObject.skeletons = [];
  23730. for (index = 0; index < scene.skeletons.length; index++) {
  23731. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  23732. }
  23733. // Geometries
  23734. serializationObject.geometries = {};
  23735. serializationObject.geometries.boxes = [];
  23736. serializationObject.geometries.spheres = [];
  23737. serializationObject.geometries.cylinders = [];
  23738. serializationObject.geometries.toruses = [];
  23739. serializationObject.geometries.grounds = [];
  23740. serializationObject.geometries.planes = [];
  23741. serializationObject.geometries.torusKnots = [];
  23742. serializationObject.geometries.vertexData = [];
  23743. serializedGeometries = [];
  23744. var geometries = scene.getGeometries();
  23745. for (index = 0; index < geometries.length; index++) {
  23746. var geometry = geometries[index];
  23747. if (geometry.isReady()) {
  23748. serializeGeometry(geometry, serializationObject.geometries);
  23749. }
  23750. }
  23751. // Meshes
  23752. serializationObject.meshes = [];
  23753. for (index = 0; index < scene.meshes.length; index++) {
  23754. var abstractMesh = scene.meshes[index];
  23755. if (abstractMesh instanceof BABYLON.Mesh) {
  23756. var mesh = abstractMesh;
  23757. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  23758. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  23759. }
  23760. }
  23761. }
  23762. // Particles Systems
  23763. serializationObject.particleSystems = [];
  23764. for (index = 0; index < scene.particleSystems.length; index++) {
  23765. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  23766. }
  23767. // Lens flares
  23768. serializationObject.lensFlareSystems = [];
  23769. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  23770. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  23771. }
  23772. // Shadows
  23773. serializationObject.shadowGenerators = [];
  23774. for (index = 0; index < scene.lights.length; index++) {
  23775. light = scene.lights[index];
  23776. if (light.getShadowGenerator()) {
  23777. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  23778. }
  23779. }
  23780. return serializationObject;
  23781. };
  23782. return SceneSerializer;
  23783. })();
  23784. BABYLON.SceneSerializer = SceneSerializer;
  23785. })(BABYLON || (BABYLON = {}));
  23786. //# sourceMappingURL=babylon.sceneSerializer.js.map
  23787. var BABYLON;
  23788. (function (BABYLON) {
  23789. // Unique ID when we import meshes from Babylon to CSG
  23790. var currentCSGMeshId = 0;
  23791. // # class Vertex
  23792. // Represents a vertex of a polygon. Use your own vertex class instead of this
  23793. // one to provide additional features like texture coordinates and vertex
  23794. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  23795. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  23796. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  23797. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  23798. // is not used anywhere else.
  23799. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  23800. var Vertex = (function () {
  23801. function Vertex(pos, normal, uv) {
  23802. this.pos = pos;
  23803. this.normal = normal;
  23804. this.uv = uv;
  23805. }
  23806. Vertex.prototype.clone = function () {
  23807. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  23808. };
  23809. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  23810. // orientation of a polygon is flipped.
  23811. Vertex.prototype.flip = function () {
  23812. this.normal = this.normal.scale(-1);
  23813. };
  23814. // Create a new vertex between this vertex and `other` by linearly
  23815. // interpolating all properties using a parameter of `t`. Subclasses should
  23816. // override this to interpolate additional properties.
  23817. Vertex.prototype.interpolate = function (other, t) {
  23818. 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));
  23819. };
  23820. return Vertex;
  23821. })();
  23822. // # class Plane
  23823. // Represents a plane in 3D space.
  23824. var Plane = (function () {
  23825. function Plane(normal, w) {
  23826. this.normal = normal;
  23827. this.w = w;
  23828. }
  23829. Plane.FromPoints = function (a, b, c) {
  23830. var v0 = c.subtract(a);
  23831. var v1 = b.subtract(a);
  23832. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  23833. return null;
  23834. }
  23835. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  23836. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  23837. };
  23838. Plane.prototype.clone = function () {
  23839. return new Plane(this.normal.clone(), this.w);
  23840. };
  23841. Plane.prototype.flip = function () {
  23842. this.normal.scaleInPlace(-1);
  23843. this.w = -this.w;
  23844. };
  23845. // Split `polygon` by this plane if needed, then put the polygon or polygon
  23846. // fragments in the appropriate lists. Coplanar polygons go into either
  23847. // `coplanarFront` or `coplanarBack` depending on their orientation with
  23848. // respect to this plane. Polygons in front or in back of this plane go into
  23849. // either `front` or `back`.
  23850. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  23851. var COPLANAR = 0;
  23852. var FRONT = 1;
  23853. var BACK = 2;
  23854. var SPANNING = 3;
  23855. // Classify each point as well as the entire polygon into one of the above
  23856. // four classes.
  23857. var polygonType = 0;
  23858. var types = [];
  23859. for (var i = 0; i < polygon.vertices.length; i++) {
  23860. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  23861. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  23862. polygonType |= type;
  23863. types.push(type);
  23864. }
  23865. // Put the polygon in the correct list, splitting it when necessary.
  23866. switch (polygonType) {
  23867. case COPLANAR:
  23868. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  23869. break;
  23870. case FRONT:
  23871. front.push(polygon);
  23872. break;
  23873. case BACK:
  23874. back.push(polygon);
  23875. break;
  23876. case SPANNING:
  23877. var f = [], b = [];
  23878. for (i = 0; i < polygon.vertices.length; i++) {
  23879. var j = (i + 1) % polygon.vertices.length;
  23880. var ti = types[i], tj = types[j];
  23881. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  23882. if (ti != BACK)
  23883. f.push(vi);
  23884. if (ti != FRONT)
  23885. b.push(ti != BACK ? vi.clone() : vi);
  23886. if ((ti | tj) == SPANNING) {
  23887. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  23888. var v = vi.interpolate(vj, t);
  23889. f.push(v);
  23890. b.push(v.clone());
  23891. }
  23892. }
  23893. if (f.length >= 3) {
  23894. var poly = new Polygon(f, polygon.shared);
  23895. if (poly.plane)
  23896. front.push(poly);
  23897. }
  23898. if (b.length >= 3) {
  23899. poly = new Polygon(b, polygon.shared);
  23900. if (poly.plane)
  23901. back.push(poly);
  23902. }
  23903. break;
  23904. }
  23905. };
  23906. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  23907. // point is on the plane.
  23908. Plane.EPSILON = 1e-5;
  23909. return Plane;
  23910. })();
  23911. // # class Polygon
  23912. // Represents a convex polygon. The vertices used to initialize a polygon must
  23913. // be coplanar and form a convex loop.
  23914. //
  23915. // Each convex polygon has a `shared` property, which is shared between all
  23916. // polygons that are clones of each other or were split from the same polygon.
  23917. // This can be used to define per-polygon properties (such as surface color).
  23918. var Polygon = (function () {
  23919. function Polygon(vertices, shared) {
  23920. this.vertices = vertices;
  23921. this.shared = shared;
  23922. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  23923. }
  23924. Polygon.prototype.clone = function () {
  23925. var vertices = this.vertices.map(function (v) { return v.clone(); });
  23926. return new Polygon(vertices, this.shared);
  23927. };
  23928. Polygon.prototype.flip = function () {
  23929. this.vertices.reverse().map(function (v) { v.flip(); });
  23930. this.plane.flip();
  23931. };
  23932. return Polygon;
  23933. })();
  23934. // # class Node
  23935. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  23936. // by picking a polygon to split along. That polygon (and all other coplanar
  23937. // polygons) are added directly to that node and the other polygons are added to
  23938. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  23939. // no distinction between internal and leaf nodes.
  23940. var Node = (function () {
  23941. function Node(polygons) {
  23942. this.plane = null;
  23943. this.front = null;
  23944. this.back = null;
  23945. this.polygons = [];
  23946. if (polygons) {
  23947. this.build(polygons);
  23948. }
  23949. }
  23950. Node.prototype.clone = function () {
  23951. var node = new Node();
  23952. node.plane = this.plane && this.plane.clone();
  23953. node.front = this.front && this.front.clone();
  23954. node.back = this.back && this.back.clone();
  23955. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  23956. return node;
  23957. };
  23958. // Convert solid space to empty space and empty space to solid space.
  23959. Node.prototype.invert = function () {
  23960. for (var i = 0; i < this.polygons.length; i++) {
  23961. this.polygons[i].flip();
  23962. }
  23963. if (this.plane) {
  23964. this.plane.flip();
  23965. }
  23966. if (this.front) {
  23967. this.front.invert();
  23968. }
  23969. if (this.back) {
  23970. this.back.invert();
  23971. }
  23972. var temp = this.front;
  23973. this.front = this.back;
  23974. this.back = temp;
  23975. };
  23976. // Recursively remove all polygons in `polygons` that are inside this BSP
  23977. // tree.
  23978. Node.prototype.clipPolygons = function (polygons) {
  23979. if (!this.plane)
  23980. return polygons.slice();
  23981. var front = [], back = [];
  23982. for (var i = 0; i < polygons.length; i++) {
  23983. this.plane.splitPolygon(polygons[i], front, back, front, back);
  23984. }
  23985. if (this.front) {
  23986. front = this.front.clipPolygons(front);
  23987. }
  23988. if (this.back) {
  23989. back = this.back.clipPolygons(back);
  23990. }
  23991. else {
  23992. back = [];
  23993. }
  23994. return front.concat(back);
  23995. };
  23996. // Remove all polygons in this BSP tree that are inside the other BSP tree
  23997. // `bsp`.
  23998. Node.prototype.clipTo = function (bsp) {
  23999. this.polygons = bsp.clipPolygons(this.polygons);
  24000. if (this.front)
  24001. this.front.clipTo(bsp);
  24002. if (this.back)
  24003. this.back.clipTo(bsp);
  24004. };
  24005. // Return a list of all polygons in this BSP tree.
  24006. Node.prototype.allPolygons = function () {
  24007. var polygons = this.polygons.slice();
  24008. if (this.front)
  24009. polygons = polygons.concat(this.front.allPolygons());
  24010. if (this.back)
  24011. polygons = polygons.concat(this.back.allPolygons());
  24012. return polygons;
  24013. };
  24014. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  24015. // new polygons are filtered down to the bottom of the tree and become new
  24016. // nodes there. Each set of polygons is partitioned using the first polygon
  24017. // (no heuristic is used to pick a good split).
  24018. Node.prototype.build = function (polygons) {
  24019. if (!polygons.length)
  24020. return;
  24021. if (!this.plane)
  24022. this.plane = polygons[0].plane.clone();
  24023. var front = [], back = [];
  24024. for (var i = 0; i < polygons.length; i++) {
  24025. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  24026. }
  24027. if (front.length) {
  24028. if (!this.front)
  24029. this.front = new Node();
  24030. this.front.build(front);
  24031. }
  24032. if (back.length) {
  24033. if (!this.back)
  24034. this.back = new Node();
  24035. this.back.build(back);
  24036. }
  24037. };
  24038. return Node;
  24039. })();
  24040. var CSG = (function () {
  24041. function CSG() {
  24042. this.polygons = new Array();
  24043. }
  24044. // Convert BABYLON.Mesh to BABYLON.CSG
  24045. CSG.FromMesh = function (mesh) {
  24046. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  24047. if (mesh instanceof BABYLON.Mesh) {
  24048. mesh.computeWorldMatrix(true);
  24049. var matrix = mesh.getWorldMatrix();
  24050. var meshPosition = mesh.position.clone();
  24051. var meshRotation = mesh.rotation.clone();
  24052. var meshRotationQuaternion = mesh.rotationQuaternion.clone();
  24053. var meshScaling = mesh.scaling.clone();
  24054. }
  24055. else {
  24056. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  24057. }
  24058. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24059. var subMeshes = mesh.subMeshes;
  24060. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  24061. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  24062. vertices = [];
  24063. for (var j = 0; j < 3; j++) {
  24064. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  24065. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  24066. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  24067. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  24068. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  24069. vertex = new Vertex(position, normal, uv);
  24070. vertices.push(vertex);
  24071. }
  24072. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  24073. // To handle the case of degenerated triangle
  24074. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  24075. if (polygon.plane)
  24076. polygons.push(polygon);
  24077. }
  24078. }
  24079. var csg = CSG.FromPolygons(polygons);
  24080. csg.matrix = matrix;
  24081. csg.position = meshPosition;
  24082. csg.rotation = meshRotation;
  24083. csg.scaling = meshScaling;
  24084. csg.rotationQuaternion = meshRotationQuaternion;
  24085. currentCSGMeshId++;
  24086. return csg;
  24087. };
  24088. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  24089. CSG.FromPolygons = function (polygons) {
  24090. var csg = new BABYLON.CSG();
  24091. csg.polygons = polygons;
  24092. return csg;
  24093. };
  24094. CSG.prototype.clone = function () {
  24095. var csg = new BABYLON.CSG();
  24096. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  24097. csg.copyTransformAttributes(this);
  24098. return csg;
  24099. };
  24100. CSG.prototype.toPolygons = function () {
  24101. return this.polygons;
  24102. };
  24103. CSG.prototype.union = function (csg) {
  24104. var a = new Node(this.clone().polygons);
  24105. var b = new Node(csg.clone().polygons);
  24106. a.clipTo(b);
  24107. b.clipTo(a);
  24108. b.invert();
  24109. b.clipTo(a);
  24110. b.invert();
  24111. a.build(b.allPolygons());
  24112. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24113. };
  24114. CSG.prototype.unionInPlace = function (csg) {
  24115. var a = new Node(this.polygons);
  24116. var b = new Node(csg.polygons);
  24117. a.clipTo(b);
  24118. b.clipTo(a);
  24119. b.invert();
  24120. b.clipTo(a);
  24121. b.invert();
  24122. a.build(b.allPolygons());
  24123. this.polygons = a.allPolygons();
  24124. };
  24125. CSG.prototype.subtract = function (csg) {
  24126. var a = new Node(this.clone().polygons);
  24127. var b = new Node(csg.clone().polygons);
  24128. a.invert();
  24129. a.clipTo(b);
  24130. b.clipTo(a);
  24131. b.invert();
  24132. b.clipTo(a);
  24133. b.invert();
  24134. a.build(b.allPolygons());
  24135. a.invert();
  24136. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24137. };
  24138. CSG.prototype.subtractInPlace = function (csg) {
  24139. var a = new Node(this.polygons);
  24140. var b = new Node(csg.polygons);
  24141. a.invert();
  24142. a.clipTo(b);
  24143. b.clipTo(a);
  24144. b.invert();
  24145. b.clipTo(a);
  24146. b.invert();
  24147. a.build(b.allPolygons());
  24148. a.invert();
  24149. this.polygons = a.allPolygons();
  24150. };
  24151. CSG.prototype.intersect = function (csg) {
  24152. var a = new Node(this.clone().polygons);
  24153. var b = new Node(csg.clone().polygons);
  24154. a.invert();
  24155. b.clipTo(a);
  24156. b.invert();
  24157. a.clipTo(b);
  24158. b.clipTo(a);
  24159. a.build(b.allPolygons());
  24160. a.invert();
  24161. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24162. };
  24163. CSG.prototype.intersectInPlace = function (csg) {
  24164. var a = new Node(this.polygons);
  24165. var b = new Node(csg.polygons);
  24166. a.invert();
  24167. b.clipTo(a);
  24168. b.invert();
  24169. a.clipTo(b);
  24170. b.clipTo(a);
  24171. a.build(b.allPolygons());
  24172. a.invert();
  24173. this.polygons = a.allPolygons();
  24174. };
  24175. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  24176. // not modified.
  24177. CSG.prototype.inverse = function () {
  24178. var csg = this.clone();
  24179. csg.inverseInPlace();
  24180. return csg;
  24181. };
  24182. CSG.prototype.inverseInPlace = function () {
  24183. this.polygons.map(function (p) { p.flip(); });
  24184. };
  24185. // This is used to keep meshes transformations so they can be restored
  24186. // when we build back a Babylon Mesh
  24187. // NB : All CSG operations are performed in world coordinates
  24188. CSG.prototype.copyTransformAttributes = function (csg) {
  24189. this.matrix = csg.matrix;
  24190. this.position = csg.position;
  24191. this.rotation = csg.rotation;
  24192. this.scaling = csg.scaling;
  24193. this.rotationQuaternion = csg.rotationQuaternion;
  24194. return this;
  24195. };
  24196. // Build Raw mesh from CSG
  24197. // Coordinates here are in world space
  24198. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  24199. var matrix = this.matrix.clone();
  24200. matrix.invert();
  24201. 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;
  24202. if (keepSubMeshes) {
  24203. // Sort Polygons, since subMeshes are indices range
  24204. polygons.sort(function (a, b) {
  24205. if (a.shared.meshId === b.shared.meshId) {
  24206. return a.shared.subMeshId - b.shared.subMeshId;
  24207. }
  24208. else {
  24209. return a.shared.meshId - b.shared.meshId;
  24210. }
  24211. });
  24212. }
  24213. for (var i = 0, il = polygons.length; i < il; i++) {
  24214. polygon = polygons[i];
  24215. // Building SubMeshes
  24216. if (!subMesh_dict[polygon.shared.meshId]) {
  24217. subMesh_dict[polygon.shared.meshId] = {};
  24218. }
  24219. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  24220. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  24221. indexStart: +Infinity,
  24222. indexEnd: -Infinity,
  24223. materialIndex: polygon.shared.materialIndex
  24224. };
  24225. }
  24226. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  24227. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  24228. polygonIndices[0] = 0;
  24229. polygonIndices[1] = j - 1;
  24230. polygonIndices[2] = j;
  24231. for (var k = 0; k < 3; k++) {
  24232. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  24233. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  24234. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  24235. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  24236. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  24237. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  24238. // Check if 2 points can be merged
  24239. if (!(typeof vertex_idx !== 'undefined' &&
  24240. normals[vertex_idx * 3] === localNormal.x &&
  24241. normals[vertex_idx * 3 + 1] === localNormal.y &&
  24242. normals[vertex_idx * 3 + 2] === localNormal.z &&
  24243. uvs[vertex_idx * 2] === uv.x &&
  24244. uvs[vertex_idx * 2 + 1] === uv.y)) {
  24245. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  24246. uvs.push(uv.x, uv.y);
  24247. normals.push(normal.x, normal.y, normal.z);
  24248. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  24249. }
  24250. indices.push(vertex_idx);
  24251. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  24252. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  24253. currentIndex++;
  24254. }
  24255. }
  24256. }
  24257. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  24258. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24259. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  24260. mesh.setIndices(indices);
  24261. if (keepSubMeshes) {
  24262. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  24263. var materialIndexOffset = 0, materialMaxIndex;
  24264. mesh.subMeshes.length = 0;
  24265. for (var m in subMesh_dict) {
  24266. materialMaxIndex = -1;
  24267. for (var sm in subMesh_dict[m]) {
  24268. subMesh_obj = subMesh_dict[m][sm];
  24269. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  24270. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  24271. }
  24272. materialIndexOffset += ++materialMaxIndex;
  24273. }
  24274. }
  24275. return mesh;
  24276. };
  24277. // Build Mesh from CSG taking material and transforms into account
  24278. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  24279. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  24280. mesh.material = material;
  24281. mesh.position.copyFrom(this.position);
  24282. mesh.rotation.copyFrom(this.rotation);
  24283. mesh.rotationQuaternion.copyFrom(this.rotationQuaternion);
  24284. mesh.scaling.copyFrom(this.scaling);
  24285. mesh.computeWorldMatrix(true);
  24286. return mesh;
  24287. };
  24288. return CSG;
  24289. })();
  24290. BABYLON.CSG = CSG;
  24291. })(BABYLON || (BABYLON = {}));
  24292. //# sourceMappingURL=babylon.csg.js.map
  24293. var __extends = this.__extends || function (d, b) {
  24294. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24295. function __() { this.constructor = d; }
  24296. __.prototype = b.prototype;
  24297. d.prototype = new __();
  24298. };
  24299. var BABYLON;
  24300. (function (BABYLON) {
  24301. var VRDistortionCorrectionPostProcess = (function (_super) {
  24302. __extends(VRDistortionCorrectionPostProcess, _super);
  24303. //ANY
  24304. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  24305. var _this = this;
  24306. _super.call(this, name, "vrDistortionCorrection", [
  24307. 'LensCenter',
  24308. 'Scale',
  24309. 'ScaleIn',
  24310. 'HmdWarpParam'
  24311. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  24312. this._isRightEye = isRightEye;
  24313. this._distortionFactors = vrMetrics.distortionK;
  24314. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  24315. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  24316. this.onSizeChanged = function () {
  24317. _this.aspectRatio = _this.width * .5 / _this.height;
  24318. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  24319. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  24320. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  24321. };
  24322. this.onApply = function (effect) {
  24323. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  24324. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  24325. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  24326. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  24327. };
  24328. }
  24329. return VRDistortionCorrectionPostProcess;
  24330. })(BABYLON.PostProcess);
  24331. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  24332. })(BABYLON || (BABYLON = {}));
  24333. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  24334. // Mainly based on these 2 articles :
  24335. // 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
  24336. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  24337. var BABYLON;
  24338. (function (BABYLON) {
  24339. (function (JoystickAxis) {
  24340. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  24341. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  24342. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  24343. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  24344. var JoystickAxis = BABYLON.JoystickAxis;
  24345. var VirtualJoystick = (function () {
  24346. function VirtualJoystick(leftJoystick) {
  24347. var _this = this;
  24348. if (leftJoystick) {
  24349. this._leftJoystick = true;
  24350. }
  24351. else {
  24352. this._leftJoystick = false;
  24353. }
  24354. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  24355. VirtualJoystick._globalJoystickIndex++;
  24356. // By default left & right arrow keys are moving the X
  24357. // and up & down keys are moving the Y
  24358. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24359. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24360. this.reverseLeftRight = false;
  24361. this.reverseUpDown = false;
  24362. // collections of pointers
  24363. this._touches = new BABYLON.SmartCollection();
  24364. this.deltaPosition = BABYLON.Vector3.Zero();
  24365. this._joystickSensibility = 25;
  24366. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24367. this._rotationSpeed = 25;
  24368. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  24369. this._rotateOnAxisRelativeToMesh = false;
  24370. // injecting a canvas element on top of the canvas 3D game
  24371. if (!VirtualJoystick.vjCanvas) {
  24372. window.addEventListener("resize", function () {
  24373. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24374. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24375. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  24376. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  24377. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  24378. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  24379. }, false);
  24380. VirtualJoystick.vjCanvas = document.createElement("canvas");
  24381. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24382. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24383. VirtualJoystick.vjCanvas.width = window.innerWidth;
  24384. VirtualJoystick.vjCanvas.height = window.innerHeight;
  24385. VirtualJoystick.vjCanvas.style.width = "100%";
  24386. VirtualJoystick.vjCanvas.style.height = "100%";
  24387. VirtualJoystick.vjCanvas.style.position = "absolute";
  24388. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  24389. VirtualJoystick.vjCanvas.style.top = "0px";
  24390. VirtualJoystick.vjCanvas.style.left = "0px";
  24391. VirtualJoystick.vjCanvas.style.zIndex = "5";
  24392. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  24393. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  24394. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  24395. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24396. document.body.appendChild(VirtualJoystick.vjCanvas);
  24397. }
  24398. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  24399. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  24400. this.pressed = false;
  24401. // default joystick color
  24402. this._joystickColor = "cyan";
  24403. this._joystickPointerID = -1;
  24404. // current joystick position
  24405. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  24406. // origin joystick position
  24407. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  24408. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  24409. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  24410. _this._onPointerDown(evt);
  24411. }, false);
  24412. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  24413. _this._onPointerMove(evt);
  24414. }, false);
  24415. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  24416. _this._onPointerUp(evt);
  24417. }, false);
  24418. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  24419. _this._onPointerUp(evt);
  24420. }, false);
  24421. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  24422. evt.preventDefault(); // Disables system menu
  24423. }, false);
  24424. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24425. }
  24426. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  24427. this._joystickSensibility = newJoystickSensibility;
  24428. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24429. };
  24430. VirtualJoystick.prototype._onPointerDown = function (e) {
  24431. var positionOnScreenCondition;
  24432. e.preventDefault();
  24433. if (this._leftJoystick === true) {
  24434. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  24435. }
  24436. else {
  24437. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  24438. }
  24439. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  24440. // First contact will be dedicated to the virtual joystick
  24441. this._joystickPointerID = e.pointerId;
  24442. this._joystickPointerStartPos.x = e.clientX;
  24443. this._joystickPointerStartPos.y = e.clientY;
  24444. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  24445. this._deltaJoystickVector.x = 0;
  24446. this._deltaJoystickVector.y = 0;
  24447. this.pressed = true;
  24448. this._touches.add(e.pointerId.toString(), e);
  24449. }
  24450. else {
  24451. // You can only trigger the action buttons with a joystick declared
  24452. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  24453. this._action();
  24454. this._touches.add(e.pointerId.toString(), e);
  24455. }
  24456. }
  24457. };
  24458. VirtualJoystick.prototype._onPointerMove = function (e) {
  24459. // If the current pointer is the one associated to the joystick (first touch contact)
  24460. if (this._joystickPointerID == e.pointerId) {
  24461. this._joystickPointerPos.x = e.clientX;
  24462. this._joystickPointerPos.y = e.clientY;
  24463. this._deltaJoystickVector = this._joystickPointerPos.clone();
  24464. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  24465. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  24466. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  24467. switch (this._axisTargetedByLeftAndRight) {
  24468. case JoystickAxis.X:
  24469. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  24470. break;
  24471. case JoystickAxis.Y:
  24472. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  24473. break;
  24474. case JoystickAxis.Z:
  24475. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  24476. break;
  24477. }
  24478. var directionUpDown = this.reverseUpDown ? 1 : -1;
  24479. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  24480. switch (this._axisTargetedByUpAndDown) {
  24481. case JoystickAxis.X:
  24482. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  24483. break;
  24484. case JoystickAxis.Y:
  24485. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  24486. break;
  24487. case JoystickAxis.Z:
  24488. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  24489. break;
  24490. }
  24491. }
  24492. else {
  24493. if (this._touches.item(e.pointerId.toString())) {
  24494. this._touches.item(e.pointerId.toString()).x = e.clientX;
  24495. this._touches.item(e.pointerId.toString()).y = e.clientY;
  24496. }
  24497. }
  24498. };
  24499. VirtualJoystick.prototype._onPointerUp = function (e) {
  24500. this._clearCanvas();
  24501. if (this._joystickPointerID == e.pointerId) {
  24502. this._joystickPointerID = -1;
  24503. this.pressed = false;
  24504. }
  24505. this._deltaJoystickVector.x = 0;
  24506. this._deltaJoystickVector.y = 0;
  24507. this._touches.remove(e.pointerId.toString());
  24508. };
  24509. /**
  24510. * Change the color of the virtual joystick
  24511. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  24512. */
  24513. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  24514. this._joystickColor = newColor;
  24515. };
  24516. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  24517. this._action = action;
  24518. };
  24519. // Define which axis you'd like to control for left & right
  24520. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  24521. switch (axis) {
  24522. case JoystickAxis.X:
  24523. case JoystickAxis.Y:
  24524. case JoystickAxis.Z:
  24525. this._axisTargetedByLeftAndRight = axis;
  24526. break;
  24527. default:
  24528. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24529. break;
  24530. }
  24531. };
  24532. // Define which axis you'd like to control for up & down
  24533. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  24534. switch (axis) {
  24535. case JoystickAxis.X:
  24536. case JoystickAxis.Y:
  24537. case JoystickAxis.Z:
  24538. this._axisTargetedByUpAndDown = axis;
  24539. break;
  24540. default:
  24541. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24542. break;
  24543. }
  24544. };
  24545. VirtualJoystick.prototype._clearCanvas = function () {
  24546. if (this._leftJoystick) {
  24547. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  24548. }
  24549. else {
  24550. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  24551. }
  24552. };
  24553. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  24554. var _this = this;
  24555. if (this.pressed) {
  24556. this._clearCanvas();
  24557. this._touches.forEach(function (touch) {
  24558. if (touch.pointerId === _this._joystickPointerID) {
  24559. VirtualJoystick.vjCanvasContext.beginPath();
  24560. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24561. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24562. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  24563. VirtualJoystick.vjCanvasContext.stroke();
  24564. VirtualJoystick.vjCanvasContext.beginPath();
  24565. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24566. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24567. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  24568. VirtualJoystick.vjCanvasContext.stroke();
  24569. VirtualJoystick.vjCanvasContext.beginPath();
  24570. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24571. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  24572. VirtualJoystick.vjCanvasContext.stroke();
  24573. }
  24574. else {
  24575. VirtualJoystick.vjCanvasContext.beginPath();
  24576. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  24577. VirtualJoystick.vjCanvasContext.beginPath();
  24578. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  24579. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24580. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  24581. VirtualJoystick.vjCanvasContext.stroke();
  24582. }
  24583. ;
  24584. });
  24585. }
  24586. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24587. };
  24588. VirtualJoystick.prototype.releaseCanvas = function () {
  24589. if (VirtualJoystick.vjCanvas) {
  24590. document.body.removeChild(VirtualJoystick.vjCanvas);
  24591. VirtualJoystick.vjCanvas = null;
  24592. }
  24593. };
  24594. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  24595. VirtualJoystick._globalJoystickIndex = 0;
  24596. return VirtualJoystick;
  24597. })();
  24598. BABYLON.VirtualJoystick = VirtualJoystick;
  24599. })(BABYLON || (BABYLON = {}));
  24600. //# sourceMappingURL=babylon.virtualJoystick.js.map
  24601. var __extends = this.__extends || function (d, b) {
  24602. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24603. function __() { this.constructor = d; }
  24604. __.prototype = b.prototype;
  24605. d.prototype = new __();
  24606. };
  24607. var BABYLON;
  24608. (function (BABYLON) {
  24609. // We're mainly based on the logic defined into the FreeCamera code
  24610. var VirtualJoysticksCamera = (function (_super) {
  24611. __extends(VirtualJoysticksCamera, _super);
  24612. function VirtualJoysticksCamera(name, position, scene) {
  24613. _super.call(this, name, position, scene);
  24614. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  24615. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  24616. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  24617. this._leftjoystick.setJoystickSensibility(0.15);
  24618. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  24619. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  24620. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  24621. this._rightjoystick.reverseUpDown = true;
  24622. this._rightjoystick.setJoystickSensibility(0.05);
  24623. this._rightjoystick.setJoystickColor("yellow");
  24624. }
  24625. VirtualJoysticksCamera.prototype._checkInputs = function () {
  24626. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24627. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  24628. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24629. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  24630. if (!this._leftjoystick.pressed) {
  24631. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  24632. }
  24633. if (!this._rightjoystick.pressed) {
  24634. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  24635. }
  24636. _super.prototype._checkInputs.call(this);
  24637. };
  24638. VirtualJoysticksCamera.prototype.dispose = function () {
  24639. this._leftjoystick.releaseCanvas();
  24640. _super.prototype.dispose.call(this);
  24641. };
  24642. return VirtualJoysticksCamera;
  24643. })(BABYLON.FreeCamera);
  24644. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  24645. })(BABYLON || (BABYLON = {}));
  24646. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  24647. var __extends = this.__extends || function (d, b) {
  24648. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  24649. function __() { this.constructor = d; }
  24650. __.prototype = b.prototype;
  24651. d.prototype = new __();
  24652. };
  24653. var BABYLON;
  24654. (function (BABYLON) {
  24655. var ShaderMaterial = (function (_super) {
  24656. __extends(ShaderMaterial, _super);
  24657. function ShaderMaterial(name, scene, shaderPath, options) {
  24658. _super.call(this, name, scene);
  24659. this._textures = new Array();
  24660. this._floats = new Array();
  24661. this._floatsArrays = {};
  24662. this._colors3 = new Array();
  24663. this._colors4 = new Array();
  24664. this._vectors2 = new Array();
  24665. this._vectors3 = new Array();
  24666. this._matrices = new Array();
  24667. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  24668. this._shaderPath = shaderPath;
  24669. options.needAlphaBlending = options.needAlphaBlending || false;
  24670. options.needAlphaTesting = options.needAlphaTesting || false;
  24671. options.attributes = options.attributes || ["position", "normal", "uv"];
  24672. options.uniforms = options.uniforms || ["worldViewProjection"];
  24673. options.samplers = options.samplers || [];
  24674. this._options = options;
  24675. }
  24676. ShaderMaterial.prototype.needAlphaBlending = function () {
  24677. return this._options.needAlphaBlending;
  24678. };
  24679. ShaderMaterial.prototype.needAlphaTesting = function () {
  24680. return this._options.needAlphaTesting;
  24681. };
  24682. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  24683. if (this._options.uniforms.indexOf(uniformName) === -1) {
  24684. this._options.uniforms.push(uniformName);
  24685. }
  24686. };
  24687. ShaderMaterial.prototype.setTexture = function (name, texture) {
  24688. if (this._options.samplers.indexOf(name) === -1) {
  24689. this._options.samplers.push(name);
  24690. }
  24691. this._textures[name] = texture;
  24692. return this;
  24693. };
  24694. ShaderMaterial.prototype.setFloat = function (name, value) {
  24695. this._checkUniform(name);
  24696. this._floats[name] = value;
  24697. return this;
  24698. };
  24699. ShaderMaterial.prototype.setFloats = function (name, value) {
  24700. this._checkUniform(name);
  24701. this._floatsArrays[name] = value;
  24702. return this;
  24703. };
  24704. ShaderMaterial.prototype.setColor3 = function (name, value) {
  24705. this._checkUniform(name);
  24706. this._colors3[name] = value;
  24707. return this;
  24708. };
  24709. ShaderMaterial.prototype.setColor4 = function (name, value) {
  24710. this._checkUniform(name);
  24711. this._colors4[name] = value;
  24712. return this;
  24713. };
  24714. ShaderMaterial.prototype.setVector2 = function (name, value) {
  24715. this._checkUniform(name);
  24716. this._vectors2[name] = value;
  24717. return this;
  24718. };
  24719. ShaderMaterial.prototype.setVector3 = function (name, value) {
  24720. this._checkUniform(name);
  24721. this._vectors3[name] = value;
  24722. return this;
  24723. };
  24724. ShaderMaterial.prototype.setMatrix = function (name, value) {
  24725. this._checkUniform(name);
  24726. this._matrices[name] = value;
  24727. return this;
  24728. };
  24729. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  24730. var scene = this.getScene();
  24731. var engine = scene.getEngine();
  24732. if (!this.checkReadyOnEveryCall) {
  24733. if (this._renderId === scene.getRenderId()) {
  24734. return true;
  24735. }
  24736. }
  24737. // Instances
  24738. var defines = [];
  24739. var fallbacks = new BABYLON.EffectFallbacks();
  24740. if (useInstances) {
  24741. defines.push("#define INSTANCES");
  24742. }
  24743. // Bones
  24744. if (mesh && mesh.useBones) {
  24745. defines.push("#define BONES");
  24746. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24747. defines.push("#define BONES4");
  24748. fallbacks.addFallback(0, "BONES4");
  24749. }
  24750. // Alpha test
  24751. if (engine.getAlphaTesting()) {
  24752. defines.push("#define ALPHATEST");
  24753. }
  24754. var previousEffect = this._effect;
  24755. var join = defines.join("\n");
  24756. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  24757. if (!this._effect.isReady()) {
  24758. return false;
  24759. }
  24760. if (previousEffect !== this._effect) {
  24761. scene.resetCachedMaterial();
  24762. }
  24763. this._renderId = scene.getRenderId();
  24764. return true;
  24765. };
  24766. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24767. var scene = this.getScene();
  24768. if (this._options.uniforms.indexOf("world") !== -1) {
  24769. this._effect.setMatrix("world", world);
  24770. }
  24771. if (this._options.uniforms.indexOf("worldView") !== -1) {
  24772. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  24773. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  24774. }
  24775. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  24776. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  24777. }
  24778. };
  24779. ShaderMaterial.prototype.bind = function (world, mesh) {
  24780. // Std values
  24781. this.bindOnlyWorldMatrix(world);
  24782. if (this.getScene().getCachedMaterial() !== this) {
  24783. if (this._options.uniforms.indexOf("view") !== -1) {
  24784. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  24785. }
  24786. if (this._options.uniforms.indexOf("projection") !== -1) {
  24787. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  24788. }
  24789. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  24790. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24791. }
  24792. // Bones
  24793. if (mesh && mesh.useBones) {
  24794. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24795. }
  24796. // Texture
  24797. for (var name in this._textures) {
  24798. this._effect.setTexture(name, this._textures[name]);
  24799. }
  24800. // Float
  24801. for (name in this._floats) {
  24802. this._effect.setFloat(name, this._floats[name]);
  24803. }
  24804. // Float s
  24805. for (name in this._floatsArrays) {
  24806. this._effect.setArray(name, this._floatsArrays[name]);
  24807. }
  24808. // Color3
  24809. for (name in this._colors3) {
  24810. this._effect.setColor3(name, this._colors3[name]);
  24811. }
  24812. // Color4
  24813. for (name in this._colors4) {
  24814. var color = this._colors4[name];
  24815. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24816. }
  24817. // Vector2
  24818. for (name in this._vectors2) {
  24819. this._effect.setVector2(name, this._vectors2[name]);
  24820. }
  24821. // Vector3
  24822. for (name in this._vectors3) {
  24823. this._effect.setVector3(name, this._vectors3[name]);
  24824. }
  24825. // Matrix
  24826. for (name in this._matrices) {
  24827. this._effect.setMatrix(name, this._matrices[name]);
  24828. }
  24829. }
  24830. _super.prototype.bind.call(this, world, mesh);
  24831. };
  24832. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  24833. for (var name in this._textures) {
  24834. this._textures[name].dispose();
  24835. }
  24836. this._textures = [];
  24837. _super.prototype.dispose.call(this, forceDisposeEffect);
  24838. };
  24839. return ShaderMaterial;
  24840. })(BABYLON.Material);
  24841. BABYLON.ShaderMaterial = ShaderMaterial;
  24842. })(BABYLON || (BABYLON = {}));
  24843. //# sourceMappingURL=babylon.shaderMaterial.js.map
  24844. var BABYLON;
  24845. (function (BABYLON) {
  24846. var VertexData = (function () {
  24847. function VertexData() {
  24848. }
  24849. VertexData.prototype.set = function (data, kind) {
  24850. switch (kind) {
  24851. case BABYLON.VertexBuffer.PositionKind:
  24852. this.positions = data;
  24853. break;
  24854. case BABYLON.VertexBuffer.NormalKind:
  24855. this.normals = data;
  24856. break;
  24857. case BABYLON.VertexBuffer.UVKind:
  24858. this.uvs = data;
  24859. break;
  24860. case BABYLON.VertexBuffer.UV2Kind:
  24861. this.uv2s = data;
  24862. break;
  24863. case BABYLON.VertexBuffer.ColorKind:
  24864. this.colors = data;
  24865. break;
  24866. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24867. this.matricesIndices = data;
  24868. break;
  24869. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24870. this.matricesWeights = data;
  24871. break;
  24872. }
  24873. };
  24874. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24875. this._applyTo(mesh, updatable);
  24876. };
  24877. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24878. this._applyTo(geometry, updatable);
  24879. };
  24880. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24881. this._update(mesh);
  24882. };
  24883. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24884. this._update(geometry);
  24885. };
  24886. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24887. if (this.positions) {
  24888. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24889. }
  24890. if (this.normals) {
  24891. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24892. }
  24893. if (this.uvs) {
  24894. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24895. }
  24896. if (this.uv2s) {
  24897. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  24898. }
  24899. if (this.colors) {
  24900. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24901. }
  24902. if (this.matricesIndices) {
  24903. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24904. }
  24905. if (this.matricesWeights) {
  24906. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24907. }
  24908. if (this.indices) {
  24909. meshOrGeometry.setIndices(this.indices);
  24910. }
  24911. };
  24912. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24913. if (this.positions) {
  24914. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24915. }
  24916. if (this.normals) {
  24917. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24918. }
  24919. if (this.uvs) {
  24920. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24921. }
  24922. if (this.uv2s) {
  24923. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  24924. }
  24925. if (this.colors) {
  24926. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24927. }
  24928. if (this.matricesIndices) {
  24929. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24930. }
  24931. if (this.matricesWeights) {
  24932. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24933. }
  24934. if (this.indices) {
  24935. meshOrGeometry.setIndices(this.indices);
  24936. }
  24937. };
  24938. VertexData.prototype.transform = function (matrix) {
  24939. var transformed = BABYLON.Vector3.Zero();
  24940. if (this.positions) {
  24941. var position = BABYLON.Vector3.Zero();
  24942. for (var index = 0; index < this.positions.length; index += 3) {
  24943. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24944. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24945. this.positions[index] = transformed.x;
  24946. this.positions[index + 1] = transformed.y;
  24947. this.positions[index + 2] = transformed.z;
  24948. }
  24949. }
  24950. if (this.normals) {
  24951. var normal = BABYLON.Vector3.Zero();
  24952. for (index = 0; index < this.normals.length; index += 3) {
  24953. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24954. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24955. this.normals[index] = transformed.x;
  24956. this.normals[index + 1] = transformed.y;
  24957. this.normals[index + 2] = transformed.z;
  24958. }
  24959. }
  24960. };
  24961. VertexData.prototype.merge = function (other) {
  24962. if (other.indices) {
  24963. if (!this.indices) {
  24964. this.indices = [];
  24965. }
  24966. var offset = this.positions ? this.positions.length / 3 : 0;
  24967. for (var index = 0; index < other.indices.length; index++) {
  24968. this.indices.push(other.indices[index] + offset);
  24969. }
  24970. }
  24971. if (other.positions) {
  24972. if (!this.positions) {
  24973. this.positions = [];
  24974. }
  24975. for (index = 0; index < other.positions.length; index++) {
  24976. this.positions.push(other.positions[index]);
  24977. }
  24978. }
  24979. if (other.normals) {
  24980. if (!this.normals) {
  24981. this.normals = [];
  24982. }
  24983. for (index = 0; index < other.normals.length; index++) {
  24984. this.normals.push(other.normals[index]);
  24985. }
  24986. }
  24987. if (other.uvs) {
  24988. if (!this.uvs) {
  24989. this.uvs = [];
  24990. }
  24991. for (index = 0; index < other.uvs.length; index++) {
  24992. this.uvs.push(other.uvs[index]);
  24993. }
  24994. }
  24995. if (other.uv2s) {
  24996. if (!this.uv2s) {
  24997. this.uv2s = [];
  24998. }
  24999. for (index = 0; index < other.uv2s.length; index++) {
  25000. this.uv2s.push(other.uv2s[index]);
  25001. }
  25002. }
  25003. if (other.matricesIndices) {
  25004. if (!this.matricesIndices) {
  25005. this.matricesIndices = [];
  25006. }
  25007. for (index = 0; index < other.matricesIndices.length; index++) {
  25008. this.matricesIndices.push(other.matricesIndices[index]);
  25009. }
  25010. }
  25011. if (other.matricesWeights) {
  25012. if (!this.matricesWeights) {
  25013. this.matricesWeights = [];
  25014. }
  25015. for (index = 0; index < other.matricesWeights.length; index++) {
  25016. this.matricesWeights.push(other.matricesWeights[index]);
  25017. }
  25018. }
  25019. if (other.colors) {
  25020. if (!this.colors) {
  25021. this.colors = [];
  25022. }
  25023. for (index = 0; index < other.colors.length; index++) {
  25024. this.colors.push(other.colors[index]);
  25025. }
  25026. }
  25027. };
  25028. // Statics
  25029. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  25030. return VertexData._ExtractFrom(mesh, copyWhenShared);
  25031. };
  25032. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  25033. return VertexData._ExtractFrom(geometry, copyWhenShared);
  25034. };
  25035. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  25036. var result = new VertexData();
  25037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25038. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  25039. }
  25040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25041. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  25042. }
  25043. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25044. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  25045. }
  25046. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25047. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  25048. }
  25049. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25050. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  25051. }
  25052. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25053. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  25054. }
  25055. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25056. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  25057. }
  25058. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25059. return result;
  25060. };
  25061. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  25062. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25063. closeArray = closeArray || false;
  25064. closePath = closePath || false;
  25065. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25066. offset = offset || defaultOffset;
  25067. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25068. var positions = [];
  25069. var indices = [];
  25070. var normals = [];
  25071. var uvs = [];
  25072. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25073. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25074. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25075. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25076. var minlg; // minimal length among all paths from pathArray
  25077. var lg = []; // array of path lengths : nb of vertex per path
  25078. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  25079. var p; // path iterator
  25080. var i; // point iterator
  25081. var j; // point iterator
  25082. // if single path in pathArray
  25083. if (pathArray.length < 2) {
  25084. var ar1 = [];
  25085. var ar2 = [];
  25086. for (i = 0; i < pathArray[0].length - offset; i++) {
  25087. ar1.push(pathArray[0][i]);
  25088. ar2.push(pathArray[0][i + offset]);
  25089. }
  25090. pathArray = [ar1, ar2];
  25091. }
  25092. // positions and horizontal distances (u)
  25093. var idc = 0;
  25094. minlg = pathArray[0].length;
  25095. for (p = 0; p < pathArray.length; p++) {
  25096. uTotalDistance[p] = 0;
  25097. us[p] = [0];
  25098. var path = pathArray[p];
  25099. var l = path.length;
  25100. minlg = (minlg < l) ? minlg : l;
  25101. lg[p] = l;
  25102. idx[p] = idc;
  25103. j = 0;
  25104. while (j < l) {
  25105. positions.push(path[j].x, path[j].y, path[j].z);
  25106. if (j > 0) {
  25107. var vectlg = path[j].subtract(path[j - 1]).length();
  25108. var dist = vectlg + uTotalDistance[p];
  25109. us[p].push(dist);
  25110. uTotalDistance[p] = dist;
  25111. }
  25112. j++;
  25113. }
  25114. if (closePath) {
  25115. vectlg = path[0].subtract(path[j - 1]).length();
  25116. dist = vectlg + uTotalDistance[p];
  25117. uTotalDistance[p] = dist;
  25118. }
  25119. idc += l;
  25120. }
  25121. // vertical distances (v)
  25122. for (i = 0; i < minlg; i++) {
  25123. vTotalDistance[i] = 0;
  25124. vs[i] = [0];
  25125. var path1;
  25126. var path2;
  25127. for (p = 0; p < pathArray.length - 1; p++) {
  25128. path1 = pathArray[p];
  25129. path2 = pathArray[p + 1];
  25130. vectlg = path2[i].subtract(path1[i]).length();
  25131. dist = vectlg + vTotalDistance[i];
  25132. vs[i].push(dist);
  25133. vTotalDistance[i] = dist;
  25134. }
  25135. if (closeArray) {
  25136. path1 = pathArray[p];
  25137. path2 = pathArray[0];
  25138. vectlg = path2[i].subtract(path1[i]).length();
  25139. dist = vectlg + vTotalDistance[i];
  25140. vTotalDistance[i] = dist;
  25141. }
  25142. }
  25143. // uvs
  25144. var u;
  25145. var v;
  25146. for (p = 0; p < pathArray.length; p++) {
  25147. for (i = 0; i < minlg; i++) {
  25148. u = us[p][i] / uTotalDistance[p];
  25149. v = vs[i][p] / vTotalDistance[i];
  25150. uvs.push(u, v);
  25151. }
  25152. }
  25153. // indices
  25154. p = 0; // path index
  25155. var pi = 0; // positions array index
  25156. var l1 = lg[p] - 1; // path1 length
  25157. var l2 = lg[p + 1] - 1; // path2 length
  25158. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25159. var shft = idx[1] - idx[0]; // shift
  25160. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  25161. var t1; // two consecutive triangles, so 4 points : point1
  25162. var t2; // point2
  25163. var t3; // point3
  25164. var t4; // point4
  25165. while (pi <= min && p < path1nb) {
  25166. // 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
  25167. t1 = pi;
  25168. t2 = pi + shft;
  25169. t3 = pi + 1;
  25170. t4 = pi + shft + 1;
  25171. indices.push(pi, pi + shft, pi + 1);
  25172. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25173. pi += 1;
  25174. if (pi === min) {
  25175. if (closePath) {
  25176. indices.push(pi, pi + shft, idx[p]);
  25177. indices.push(idx[p] + shft, idx[p], pi + shft);
  25178. t3 = idx[p];
  25179. t4 = idx[p] + shft;
  25180. }
  25181. p++;
  25182. if (p === lg.length - 1) {
  25183. shft = idx[0] - idx[p];
  25184. l1 = lg[p] - 1;
  25185. l2 = lg[0] - 1;
  25186. }
  25187. else {
  25188. shft = idx[p + 1] - idx[p];
  25189. l1 = lg[p] - 1;
  25190. l2 = lg[p + 1] - 1;
  25191. }
  25192. pi = idx[p];
  25193. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25194. }
  25195. }
  25196. // normals
  25197. VertexData.ComputeNormals(positions, indices, normals);
  25198. // sides
  25199. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25200. // Result
  25201. var vertexData = new VertexData();
  25202. vertexData.indices = indices;
  25203. vertexData.positions = positions;
  25204. vertexData.normals = normals;
  25205. vertexData.uvs = uvs;
  25206. return vertexData;
  25207. };
  25208. VertexData.CreateBox = function (size, sideOrientation) {
  25209. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25210. var normalsSource = [
  25211. new BABYLON.Vector3(0, 0, 1),
  25212. new BABYLON.Vector3(0, 0, -1),
  25213. new BABYLON.Vector3(1, 0, 0),
  25214. new BABYLON.Vector3(-1, 0, 0),
  25215. new BABYLON.Vector3(0, 1, 0),
  25216. new BABYLON.Vector3(0, -1, 0)
  25217. ];
  25218. var indices = [];
  25219. var positions = [];
  25220. var normals = [];
  25221. var uvs = [];
  25222. size = size || 1;
  25223. // Create each face in turn.
  25224. for (var index = 0; index < normalsSource.length; index++) {
  25225. var normal = normalsSource[index];
  25226. // Get two vectors perpendicular to the face normal and to each other.
  25227. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25228. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25229. // Six indices (two triangles) per face.
  25230. var verticesLength = positions.length / 3;
  25231. indices.push(verticesLength);
  25232. indices.push(verticesLength + 1);
  25233. indices.push(verticesLength + 2);
  25234. indices.push(verticesLength);
  25235. indices.push(verticesLength + 2);
  25236. indices.push(verticesLength + 3);
  25237. // Four vertices per face.
  25238. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  25239. positions.push(vertex.x, vertex.y, vertex.z);
  25240. normals.push(normal.x, normal.y, normal.z);
  25241. uvs.push(1.0, 1.0);
  25242. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  25243. positions.push(vertex.x, vertex.y, vertex.z);
  25244. normals.push(normal.x, normal.y, normal.z);
  25245. uvs.push(0.0, 1.0);
  25246. vertex = normal.add(side1).add(side2).scale(size / 2);
  25247. positions.push(vertex.x, vertex.y, vertex.z);
  25248. normals.push(normal.x, normal.y, normal.z);
  25249. uvs.push(0.0, 0.0);
  25250. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  25251. positions.push(vertex.x, vertex.y, vertex.z);
  25252. normals.push(normal.x, normal.y, normal.z);
  25253. uvs.push(1.0, 0.0);
  25254. }
  25255. // sides
  25256. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25257. // Result
  25258. var vertexData = new VertexData();
  25259. vertexData.indices = indices;
  25260. vertexData.positions = positions;
  25261. vertexData.normals = normals;
  25262. vertexData.uvs = uvs;
  25263. return vertexData;
  25264. };
  25265. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  25266. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25267. segments = segments || 32;
  25268. diameter = diameter || 1;
  25269. var radius = diameter / 2;
  25270. var totalZRotationSteps = 2 + segments;
  25271. var totalYRotationSteps = 2 * totalZRotationSteps;
  25272. var indices = [];
  25273. var positions = [];
  25274. var normals = [];
  25275. var uvs = [];
  25276. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25277. var normalizedZ = zRotationStep / totalZRotationSteps;
  25278. var angleZ = (normalizedZ * Math.PI);
  25279. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25280. var normalizedY = yRotationStep / totalYRotationSteps;
  25281. var angleY = normalizedY * Math.PI * 2;
  25282. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25283. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25284. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25285. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25286. var vertex = complete.scale(radius);
  25287. var normal = BABYLON.Vector3.Normalize(vertex);
  25288. positions.push(vertex.x, vertex.y, vertex.z);
  25289. normals.push(normal.x, normal.y, normal.z);
  25290. uvs.push(normalizedZ, normalizedY);
  25291. }
  25292. if (zRotationStep > 0) {
  25293. var verticesCount = positions.length / 3;
  25294. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25295. indices.push((firstIndex));
  25296. indices.push((firstIndex + 1));
  25297. indices.push(firstIndex + totalYRotationSteps + 1);
  25298. indices.push((firstIndex + totalYRotationSteps + 1));
  25299. indices.push((firstIndex + 1));
  25300. indices.push((firstIndex + totalYRotationSteps + 2));
  25301. }
  25302. }
  25303. }
  25304. // Sides
  25305. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25306. // Result
  25307. var vertexData = new VertexData();
  25308. vertexData.indices = indices;
  25309. vertexData.positions = positions;
  25310. vertexData.normals = normals;
  25311. vertexData.uvs = uvs;
  25312. return vertexData;
  25313. };
  25314. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  25315. if (subdivisions === void 0) { subdivisions = 1; }
  25316. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25317. var radiusTop = diameterTop / 2;
  25318. var radiusBottom = diameterBottom / 2;
  25319. var indices = [];
  25320. var positions = [];
  25321. var normals = [];
  25322. var uvs = [];
  25323. height = height || 1;
  25324. diameterTop = diameterTop || 0.5;
  25325. diameterBottom = diameterBottom || 1;
  25326. tessellation = tessellation || 16;
  25327. subdivisions = subdivisions || 1;
  25328. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  25329. var getCircleVector = function (i) {
  25330. var angle = (i * 2.0 * Math.PI / tessellation);
  25331. var dx = Math.cos(angle);
  25332. var dz = Math.sin(angle);
  25333. return new BABYLON.Vector3(dx, 0, dz);
  25334. };
  25335. var createCylinderCap = function (isTop) {
  25336. var radius = isTop ? radiusTop : radiusBottom;
  25337. if (radius === 0) {
  25338. return;
  25339. }
  25340. var vbase = positions.length / 3;
  25341. var offset = new BABYLON.Vector3(0, height / 2, 0);
  25342. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25343. if (!isTop) {
  25344. offset.scaleInPlace(-1);
  25345. textureScale.x = -textureScale.x;
  25346. }
  25347. // Positions, normals & uvs
  25348. for (var i = 0; i < tessellation; i++) {
  25349. var circleVector = getCircleVector(i);
  25350. var position = circleVector.scale(radius).add(offset);
  25351. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  25352. positions.push(position.x, position.y, position.z);
  25353. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25354. }
  25355. // Indices
  25356. for (i = 0; i < tessellation - 2; i++) {
  25357. if (!isTop) {
  25358. indices.push(vbase);
  25359. indices.push(vbase + (i + 2) % tessellation);
  25360. indices.push(vbase + (i + 1) % tessellation);
  25361. }
  25362. else {
  25363. indices.push(vbase);
  25364. indices.push(vbase + (i + 1) % tessellation);
  25365. indices.push(vbase + (i + 2) % tessellation);
  25366. }
  25367. }
  25368. };
  25369. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  25370. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  25371. var stride = tessellation + 1;
  25372. // Positions, normals & uvs
  25373. for (var i = 0; i <= tessellation; i++) {
  25374. var circleVector = getCircleVector(i);
  25375. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  25376. var position, radius = radiusBottom;
  25377. for (var s = 0; s <= subdivisions; s++) {
  25378. // Update variables
  25379. position = circleVector.scale(radius);
  25380. position.addInPlace(base.add(offset.scale(s)));
  25381. textureCoordinate.y += 1 / subdivisions;
  25382. radius += (radiusTop - radiusBottom) / subdivisions;
  25383. // Push in arrays
  25384. positions.push(position.x, position.y, position.z);
  25385. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25386. }
  25387. }
  25388. subdivisions += 1;
  25389. // Indices
  25390. for (s = 0; s < subdivisions - 1; s++) {
  25391. for (i = 0; i <= tessellation; i++) {
  25392. indices.push(i * subdivisions + s);
  25393. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25394. indices.push(i * subdivisions + (s + 1));
  25395. indices.push(i * subdivisions + (s + 1));
  25396. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25397. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  25398. }
  25399. }
  25400. // Create flat triangle fan caps to seal the top and bottom.
  25401. createCylinderCap(true);
  25402. createCylinderCap(false);
  25403. // Normals
  25404. VertexData.ComputeNormals(positions, indices, normals);
  25405. // Sides
  25406. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25407. // Result
  25408. var vertexData = new VertexData();
  25409. vertexData.indices = indices;
  25410. vertexData.positions = positions;
  25411. vertexData.normals = normals;
  25412. vertexData.uvs = uvs;
  25413. return vertexData;
  25414. };
  25415. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  25416. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25417. var indices = [];
  25418. var positions = [];
  25419. var normals = [];
  25420. var uvs = [];
  25421. diameter = diameter || 1;
  25422. thickness = thickness || 0.5;
  25423. tessellation = tessellation || 16;
  25424. var stride = tessellation + 1;
  25425. for (var i = 0; i <= tessellation; i++) {
  25426. var u = i / tessellation;
  25427. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25428. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25429. for (var j = 0; j <= tessellation; j++) {
  25430. var v = 1 - j / tessellation;
  25431. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25432. var dx = Math.cos(innerAngle);
  25433. var dy = Math.sin(innerAngle);
  25434. // Create a vertex.
  25435. var normal = new BABYLON.Vector3(dx, dy, 0);
  25436. var position = normal.scale(thickness / 2);
  25437. var textureCoordinate = new BABYLON.Vector2(u, v);
  25438. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25439. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25440. positions.push(position.x, position.y, position.z);
  25441. normals.push(normal.x, normal.y, normal.z);
  25442. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25443. // And create indices for two triangles.
  25444. var nextI = (i + 1) % stride;
  25445. var nextJ = (j + 1) % stride;
  25446. indices.push(i * stride + j);
  25447. indices.push(i * stride + nextJ);
  25448. indices.push(nextI * stride + j);
  25449. indices.push(i * stride + nextJ);
  25450. indices.push(nextI * stride + nextJ);
  25451. indices.push(nextI * stride + j);
  25452. }
  25453. }
  25454. // Sides
  25455. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25456. // Result
  25457. var vertexData = new VertexData();
  25458. vertexData.indices = indices;
  25459. vertexData.positions = positions;
  25460. vertexData.normals = normals;
  25461. vertexData.uvs = uvs;
  25462. return vertexData;
  25463. };
  25464. VertexData.CreateLines = function (points) {
  25465. var indices = [];
  25466. var positions = [];
  25467. for (var index = 0; index < points.length; index++) {
  25468. positions.push(points[index].x, points[index].y, points[index].z);
  25469. if (index > 0) {
  25470. indices.push(index - 1);
  25471. indices.push(index);
  25472. }
  25473. }
  25474. // Result
  25475. var vertexData = new VertexData();
  25476. vertexData.indices = indices;
  25477. vertexData.positions = positions;
  25478. return vertexData;
  25479. };
  25480. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  25481. dashSize = dashSize || 3;
  25482. gapSize = gapSize || 1;
  25483. dashNb = dashNb || 200;
  25484. var positions = new Array();
  25485. var indices = new Array();
  25486. var curvect = BABYLON.Vector3.Zero();
  25487. var lg = 0;
  25488. var nb = 0;
  25489. var shft = 0;
  25490. var dashshft = 0;
  25491. var curshft = 0;
  25492. var idx = 0;
  25493. var i = 0;
  25494. for (i = 0; i < points.length - 1; i++) {
  25495. points[i + 1].subtractToRef(points[i], curvect);
  25496. lg += curvect.length();
  25497. }
  25498. shft = lg / dashNb;
  25499. dashshft = dashSize * shft / (dashSize + gapSize);
  25500. for (i = 0; i < points.length - 1; i++) {
  25501. points[i + 1].subtractToRef(points[i], curvect);
  25502. curvect.normalize();
  25503. nb = Math.floor(curvect.length() / shft);
  25504. for (var j = 0; j < nb; j++) {
  25505. curshft = shft * j;
  25506. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25507. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25508. indices.push(idx, idx + 1);
  25509. idx += 2;
  25510. }
  25511. }
  25512. // Result
  25513. var vertexData = new VertexData();
  25514. vertexData.positions = positions;
  25515. vertexData.indices = indices;
  25516. return vertexData;
  25517. };
  25518. VertexData.CreateGround = function (width, height, subdivisions) {
  25519. var indices = [];
  25520. var positions = [];
  25521. var normals = [];
  25522. var uvs = [];
  25523. var row, col;
  25524. width = width || 1;
  25525. height = height || 1;
  25526. subdivisions = subdivisions || 1;
  25527. for (row = 0; row <= subdivisions; row++) {
  25528. for (col = 0; col <= subdivisions; col++) {
  25529. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25530. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25531. positions.push(position.x, position.y, position.z);
  25532. normals.push(normal.x, normal.y, normal.z);
  25533. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25534. }
  25535. }
  25536. for (row = 0; row < subdivisions; row++) {
  25537. for (col = 0; col < subdivisions; col++) {
  25538. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25539. indices.push(col + 1 + row * (subdivisions + 1));
  25540. indices.push(col + row * (subdivisions + 1));
  25541. indices.push(col + (row + 1) * (subdivisions + 1));
  25542. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25543. indices.push(col + row * (subdivisions + 1));
  25544. }
  25545. }
  25546. // Result
  25547. var vertexData = new VertexData();
  25548. vertexData.indices = indices;
  25549. vertexData.positions = positions;
  25550. vertexData.normals = normals;
  25551. vertexData.uvs = uvs;
  25552. return vertexData;
  25553. };
  25554. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  25555. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  25556. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  25557. var indices = [];
  25558. var positions = [];
  25559. var normals = [];
  25560. var uvs = [];
  25561. var row, col, tileRow, tileCol;
  25562. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25563. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25564. precision.w = (precision.w < 1) ? 1 : precision.w;
  25565. precision.h = (precision.h < 1) ? 1 : precision.h;
  25566. var tileSize = {
  25567. 'w': (xmax - xmin) / subdivisions.w,
  25568. 'h': (zmax - zmin) / subdivisions.h
  25569. };
  25570. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25571. // Indices
  25572. var base = positions.length / 3;
  25573. var rowLength = precision.w + 1;
  25574. for (row = 0; row < precision.h; row++) {
  25575. for (col = 0; col < precision.w; col++) {
  25576. var square = [
  25577. base + col + row * rowLength,
  25578. base + (col + 1) + row * rowLength,
  25579. base + (col + 1) + (row + 1) * rowLength,
  25580. base + col + (row + 1) * rowLength
  25581. ];
  25582. indices.push(square[1]);
  25583. indices.push(square[2]);
  25584. indices.push(square[3]);
  25585. indices.push(square[0]);
  25586. indices.push(square[1]);
  25587. indices.push(square[3]);
  25588. }
  25589. }
  25590. // Position, normals and uvs
  25591. var position = BABYLON.Vector3.Zero();
  25592. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25593. for (row = 0; row <= precision.h; row++) {
  25594. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25595. for (col = 0; col <= precision.w; col++) {
  25596. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25597. position.y = 0;
  25598. positions.push(position.x, position.y, position.z);
  25599. normals.push(normal.x, normal.y, normal.z);
  25600. uvs.push(col / precision.w, row / precision.h);
  25601. }
  25602. }
  25603. }
  25604. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25605. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25606. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25607. }
  25608. }
  25609. // Result
  25610. var vertexData = new VertexData();
  25611. vertexData.indices = indices;
  25612. vertexData.positions = positions;
  25613. vertexData.normals = normals;
  25614. vertexData.uvs = uvs;
  25615. return vertexData;
  25616. };
  25617. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  25618. var indices = [];
  25619. var positions = [];
  25620. var normals = [];
  25621. var uvs = [];
  25622. var row, col;
  25623. // Vertices
  25624. for (row = 0; row <= subdivisions; row++) {
  25625. for (col = 0; col <= subdivisions; col++) {
  25626. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25627. // Compute height
  25628. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  25629. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  25630. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  25631. var r = buffer[pos] / 255.0;
  25632. var g = buffer[pos + 1] / 255.0;
  25633. var b = buffer[pos + 2] / 255.0;
  25634. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25635. position.y = minHeight + (maxHeight - minHeight) * gradient;
  25636. // Add vertex
  25637. positions.push(position.x, position.y, position.z);
  25638. normals.push(0, 0, 0);
  25639. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25640. }
  25641. }
  25642. // Indices
  25643. for (row = 0; row < subdivisions; row++) {
  25644. for (col = 0; col < subdivisions; col++) {
  25645. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25646. indices.push(col + 1 + row * (subdivisions + 1));
  25647. indices.push(col + row * (subdivisions + 1));
  25648. indices.push(col + (row + 1) * (subdivisions + 1));
  25649. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25650. indices.push(col + row * (subdivisions + 1));
  25651. }
  25652. }
  25653. // Normals
  25654. VertexData.ComputeNormals(positions, indices, normals);
  25655. // Result
  25656. var vertexData = new VertexData();
  25657. vertexData.indices = indices;
  25658. vertexData.positions = positions;
  25659. vertexData.normals = normals;
  25660. vertexData.uvs = uvs;
  25661. return vertexData;
  25662. };
  25663. VertexData.CreatePlane = function (size, sideOrientation) {
  25664. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25665. var indices = [];
  25666. var positions = [];
  25667. var normals = [];
  25668. var uvs = [];
  25669. size = size || 1;
  25670. // Vertices
  25671. var halfSize = size / 2.0;
  25672. positions.push(-halfSize, -halfSize, 0);
  25673. normals.push(0, 0, -1.0);
  25674. uvs.push(0.0, 0.0);
  25675. positions.push(halfSize, -halfSize, 0);
  25676. normals.push(0, 0, -1.0);
  25677. uvs.push(1.0, 0.0);
  25678. positions.push(halfSize, halfSize, 0);
  25679. normals.push(0, 0, -1.0);
  25680. uvs.push(1.0, 1.0);
  25681. positions.push(-halfSize, halfSize, 0);
  25682. normals.push(0, 0, -1.0);
  25683. uvs.push(0.0, 1.0);
  25684. // Indices
  25685. indices.push(0);
  25686. indices.push(1);
  25687. indices.push(2);
  25688. indices.push(0);
  25689. indices.push(2);
  25690. indices.push(3);
  25691. // Sides
  25692. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25693. // Result
  25694. var vertexData = new VertexData();
  25695. vertexData.indices = indices;
  25696. vertexData.positions = positions;
  25697. vertexData.normals = normals;
  25698. vertexData.uvs = uvs;
  25699. return vertexData;
  25700. };
  25701. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  25702. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25703. var positions = [];
  25704. var indices = [];
  25705. var normals = [];
  25706. var uvs = [];
  25707. // positions and uvs
  25708. positions.push(0, 0, 0); // disc center first
  25709. uvs.push(0.5, 0.5);
  25710. var step = Math.PI * 2 / tessellation;
  25711. for (var a = 0; a < Math.PI * 2; a += step) {
  25712. var x = Math.cos(a);
  25713. var y = Math.sin(a);
  25714. var u = (x + 1) / 2;
  25715. var v = (1 - y) / 2;
  25716. positions.push(radius * x, radius * y, 0);
  25717. uvs.push(u, v);
  25718. }
  25719. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25720. uvs.push(uvs[2], uvs[3]);
  25721. //indices
  25722. var vertexNb = positions.length / 3;
  25723. for (var i = 1; i < vertexNb - 1; i++) {
  25724. indices.push(i + 1, 0, i);
  25725. }
  25726. // result
  25727. VertexData.ComputeNormals(positions, indices, normals);
  25728. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25729. var vertexData = new VertexData();
  25730. vertexData.indices = indices;
  25731. vertexData.positions = positions;
  25732. vertexData.normals = normals;
  25733. vertexData.uvs = uvs;
  25734. return vertexData;
  25735. };
  25736. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25737. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  25738. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25739. var indices = [];
  25740. var positions = [];
  25741. var normals = [];
  25742. var uvs = [];
  25743. radius = radius || 2;
  25744. tube = tube || 0.5;
  25745. radialSegments = radialSegments || 32;
  25746. tubularSegments = tubularSegments || 32;
  25747. p = p || 2;
  25748. q = q || 3;
  25749. // Helper
  25750. var getPos = function (angle) {
  25751. var cu = Math.cos(angle);
  25752. var su = Math.sin(angle);
  25753. var quOverP = q / p * angle;
  25754. var cs = Math.cos(quOverP);
  25755. var tx = radius * (2 + cs) * 0.5 * cu;
  25756. var ty = radius * (2 + cs) * su * 0.5;
  25757. var tz = radius * Math.sin(quOverP) * 0.5;
  25758. return new BABYLON.Vector3(tx, ty, tz);
  25759. };
  25760. // Vertices
  25761. for (var i = 0; i <= radialSegments; i++) {
  25762. var modI = i % radialSegments;
  25763. var u = modI / radialSegments * 2 * p * Math.PI;
  25764. var p1 = getPos(u);
  25765. var p2 = getPos(u + 0.01);
  25766. var tang = p2.subtract(p1);
  25767. var n = p2.add(p1);
  25768. var bitan = BABYLON.Vector3.Cross(tang, n);
  25769. n = BABYLON.Vector3.Cross(bitan, tang);
  25770. bitan.normalize();
  25771. n.normalize();
  25772. for (var j = 0; j < tubularSegments; j++) {
  25773. var modJ = j % tubularSegments;
  25774. var v = modJ / tubularSegments * 2 * Math.PI;
  25775. var cx = -tube * Math.cos(v);
  25776. var cy = tube * Math.sin(v);
  25777. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25778. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25779. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25780. uvs.push(i / radialSegments);
  25781. uvs.push(j / tubularSegments);
  25782. }
  25783. }
  25784. for (i = 0; i < radialSegments; i++) {
  25785. for (j = 0; j < tubularSegments; j++) {
  25786. var jNext = (j + 1) % tubularSegments;
  25787. var a = i * tubularSegments + j;
  25788. var b = (i + 1) * tubularSegments + j;
  25789. var c = (i + 1) * tubularSegments + jNext;
  25790. var d = i * tubularSegments + jNext;
  25791. indices.push(d);
  25792. indices.push(b);
  25793. indices.push(a);
  25794. indices.push(d);
  25795. indices.push(c);
  25796. indices.push(b);
  25797. }
  25798. }
  25799. // Normals
  25800. VertexData.ComputeNormals(positions, indices, normals);
  25801. // Sides
  25802. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25803. // Result
  25804. var vertexData = new VertexData();
  25805. vertexData.indices = indices;
  25806. vertexData.positions = positions;
  25807. vertexData.normals = normals;
  25808. vertexData.uvs = uvs;
  25809. return vertexData;
  25810. };
  25811. // Tools
  25812. /**
  25813. * @param {any} - positions (number[] or Float32Array)
  25814. * @param {any} - indices (number[] or Uint16Array)
  25815. * @param {any} - normals (number[] or Float32Array)
  25816. */
  25817. VertexData.ComputeNormals = function (positions, indices, normals) {
  25818. var index = 0;
  25819. // temp Vector3
  25820. var p1 = BABYLON.Vector3.Zero();
  25821. var p2 = BABYLON.Vector3.Zero();
  25822. var p3 = BABYLON.Vector3.Zero();
  25823. var p1p2 = BABYLON.Vector3.Zero();
  25824. var p3p2 = BABYLON.Vector3.Zero();
  25825. var faceNormal = BABYLON.Vector3.Zero();
  25826. var vertexNormali1 = BABYLON.Vector3.Zero();
  25827. var vertexNormali2 = BABYLON.Vector3.Zero();
  25828. var vertexNormali3 = BABYLON.Vector3.Zero();
  25829. // indice triplet = 1 face
  25830. var nbFaces = indices.length / 3;
  25831. for (index = 0; index < nbFaces; index++) {
  25832. var i1 = indices[index * 3];
  25833. var i2 = indices[index * 3 + 1];
  25834. var i3 = indices[index * 3 + 2];
  25835. // setting the temp V3
  25836. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  25837. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  25838. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  25839. p1.subtractToRef(p2, p1p2);
  25840. p3.subtractToRef(p2, p3p2);
  25841. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  25842. faceNormal.normalize();
  25843. // All intermediate results are stored in the normals array :
  25844. // get the normals at i1, i2 and i3 indexes
  25845. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  25846. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  25847. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  25848. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  25849. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  25850. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  25851. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  25852. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  25853. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  25854. // make intermediate vectors3 from normals values
  25855. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  25856. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  25857. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  25858. // add the current face normals to these intermediate vectors3
  25859. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  25860. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  25861. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  25862. // store back intermediate vectors3 into the normals array
  25863. normals[i1 * 3] = vertexNormali1.x;
  25864. normals[i1 * 3 + 1] = vertexNormali1.y;
  25865. normals[i1 * 3 + 2] = vertexNormali1.z;
  25866. normals[i2 * 3] = vertexNormali2.x;
  25867. normals[i2 * 3 + 1] = vertexNormali2.y;
  25868. normals[i2 * 3 + 2] = vertexNormali2.z;
  25869. normals[i3 * 3] = vertexNormali3.x;
  25870. normals[i3 * 3 + 1] = vertexNormali3.y;
  25871. normals[i3 * 3 + 2] = vertexNormali3.z;
  25872. }
  25873. // last normalization
  25874. for (index = 0; index < normals.length / 3; index++) {
  25875. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  25876. vertexNormali1.normalize();
  25877. normals[index * 3] = vertexNormali1.x;
  25878. normals[index * 3 + 1] = vertexNormali1.y;
  25879. normals[index * 3 + 2] = vertexNormali1.z;
  25880. }
  25881. };
  25882. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25883. var li = indices.length;
  25884. var ln = normals.length;
  25885. var i;
  25886. var n;
  25887. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25888. switch (sideOrientation) {
  25889. case BABYLON.Mesh.FRONTSIDE:
  25890. // nothing changed
  25891. break;
  25892. case BABYLON.Mesh.BACKSIDE:
  25893. var tmp;
  25894. // indices
  25895. for (i = 0; i < li; i += 3) {
  25896. tmp = indices[i];
  25897. indices[i] = indices[i + 2];
  25898. indices[i + 2] = tmp;
  25899. }
  25900. // normals
  25901. for (n = 0; n < ln; n++) {
  25902. normals[n] = -normals[n];
  25903. }
  25904. break;
  25905. case BABYLON.Mesh.DOUBLESIDE:
  25906. // positions
  25907. var lp = positions.length;
  25908. var l = lp / 3;
  25909. for (var p = 0; p < lp; p++) {
  25910. positions[lp + p] = positions[p];
  25911. }
  25912. // indices
  25913. for (i = 0; i < li; i += 3) {
  25914. indices[i + li] = indices[i + 2] + l;
  25915. indices[i + 1 + li] = indices[i + 1] + l;
  25916. indices[i + 2 + li] = indices[i] + l;
  25917. }
  25918. // normals
  25919. for (n = 0; n < ln; n++) {
  25920. normals[ln + n] = -normals[n];
  25921. }
  25922. // uvs
  25923. var lu = uvs.length;
  25924. for (var u = 0; u < lu; u++) {
  25925. uvs[u + lu] = uvs[u];
  25926. }
  25927. break;
  25928. }
  25929. };
  25930. return VertexData;
  25931. })();
  25932. BABYLON.VertexData = VertexData;
  25933. })(BABYLON || (BABYLON = {}));
  25934. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25935. var __extends = this.__extends || function (d, b) {
  25936. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25937. function __() { this.constructor = d; }
  25938. __.prototype = b.prototype;
  25939. d.prototype = new __();
  25940. };
  25941. var BABYLON;
  25942. (function (BABYLON) {
  25943. var AnaglyphFreeCamera = (function (_super) {
  25944. __extends(AnaglyphFreeCamera, _super);
  25945. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  25946. _super.call(this, name, position, scene);
  25947. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25948. }
  25949. return AnaglyphFreeCamera;
  25950. })(BABYLON.FreeCamera);
  25951. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  25952. var AnaglyphArcRotateCamera = (function (_super) {
  25953. __extends(AnaglyphArcRotateCamera, _super);
  25954. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  25955. _super.call(this, name, alpha, beta, radius, target, scene);
  25956. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25957. }
  25958. return AnaglyphArcRotateCamera;
  25959. })(BABYLON.ArcRotateCamera);
  25960. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  25961. var AnaglyphGamepadCamera = (function (_super) {
  25962. __extends(AnaglyphGamepadCamera, _super);
  25963. function AnaglyphGamepadCamera(name, position, eyeSpace, scene) {
  25964. _super.call(this, name, position, scene);
  25965. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25966. }
  25967. return AnaglyphGamepadCamera;
  25968. })(BABYLON.GamepadCamera);
  25969. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  25970. })(BABYLON || (BABYLON = {}));
  25971. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  25972. var __extends = this.__extends || function (d, b) {
  25973. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25974. function __() { this.constructor = d; }
  25975. __.prototype = b.prototype;
  25976. d.prototype = new __();
  25977. };
  25978. var BABYLON;
  25979. (function (BABYLON) {
  25980. var AnaglyphPostProcess = (function (_super) {
  25981. __extends(AnaglyphPostProcess, _super);
  25982. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25983. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  25984. }
  25985. return AnaglyphPostProcess;
  25986. })(BABYLON.PostProcess);
  25987. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  25988. })(BABYLON || (BABYLON = {}));
  25989. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  25990. var BABYLON;
  25991. (function (BABYLON) {
  25992. var Tags = (function () {
  25993. function Tags() {
  25994. }
  25995. Tags.EnableFor = function (obj) {
  25996. obj._tags = obj._tags || {};
  25997. obj.hasTags = function () {
  25998. return Tags.HasTags(obj);
  25999. };
  26000. obj.addTags = function (tagsString) {
  26001. return Tags.AddTagsTo(obj, tagsString);
  26002. };
  26003. obj.removeTags = function (tagsString) {
  26004. return Tags.RemoveTagsFrom(obj, tagsString);
  26005. };
  26006. obj.matchesTagsQuery = function (tagsQuery) {
  26007. return Tags.MatchesQuery(obj, tagsQuery);
  26008. };
  26009. };
  26010. Tags.DisableFor = function (obj) {
  26011. delete obj._tags;
  26012. delete obj.hasTags;
  26013. delete obj.addTags;
  26014. delete obj.removeTags;
  26015. delete obj.matchesTagsQuery;
  26016. };
  26017. Tags.HasTags = function (obj) {
  26018. if (!obj._tags) {
  26019. return false;
  26020. }
  26021. return !BABYLON.Tools.IsEmpty(obj._tags);
  26022. };
  26023. Tags.GetTags = function (obj) {
  26024. if (!obj._tags) {
  26025. return null;
  26026. }
  26027. return obj._tags;
  26028. };
  26029. // the tags 'true' and 'false' are reserved and cannot be used as tags
  26030. // a tag cannot start with '||', '&&', and '!'
  26031. // it cannot contain whitespaces
  26032. Tags.AddTagsTo = function (obj, tagsString) {
  26033. if (!tagsString) {
  26034. return;
  26035. }
  26036. var tags = tagsString.split(" ");
  26037. for (var t in tags) {
  26038. Tags._AddTagTo(obj, tags[t]);
  26039. }
  26040. };
  26041. Tags._AddTagTo = function (obj, tag) {
  26042. tag = tag.trim();
  26043. if (tag === "" || tag === "true" || tag === "false") {
  26044. return;
  26045. }
  26046. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  26047. return;
  26048. }
  26049. Tags.EnableFor(obj);
  26050. obj._tags[tag] = true;
  26051. };
  26052. Tags.RemoveTagsFrom = function (obj, tagsString) {
  26053. if (!Tags.HasTags(obj)) {
  26054. return;
  26055. }
  26056. var tags = tagsString.split(" ");
  26057. for (var t in tags) {
  26058. Tags._RemoveTagFrom(obj, tags[t]);
  26059. }
  26060. };
  26061. Tags._RemoveTagFrom = function (obj, tag) {
  26062. delete obj._tags[tag];
  26063. };
  26064. Tags.MatchesQuery = function (obj, tagsQuery) {
  26065. if (tagsQuery === undefined) {
  26066. return true;
  26067. }
  26068. if (tagsQuery === "") {
  26069. return Tags.HasTags(obj);
  26070. }
  26071. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  26072. };
  26073. return Tags;
  26074. })();
  26075. BABYLON.Tags = Tags;
  26076. })(BABYLON || (BABYLON = {}));
  26077. //# sourceMappingURL=babylon.tags.js.map
  26078. var BABYLON;
  26079. (function (BABYLON) {
  26080. var Internals;
  26081. (function (Internals) {
  26082. var AndOrNotEvaluator = (function () {
  26083. function AndOrNotEvaluator() {
  26084. }
  26085. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  26086. if (!query.match(/\([^\(\)]*\)/g)) {
  26087. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  26088. }
  26089. else {
  26090. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  26091. // remove parenthesis
  26092. r = r.slice(1, r.length - 1);
  26093. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  26094. });
  26095. }
  26096. if (query === "true") {
  26097. return true;
  26098. }
  26099. if (query === "false") {
  26100. return false;
  26101. }
  26102. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  26103. };
  26104. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  26105. evaluateCallback = evaluateCallback || (function (r) {
  26106. return r === "true" ? true : false;
  26107. });
  26108. var result;
  26109. var or = parenthesisContent.split("||");
  26110. for (var i in or) {
  26111. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  26112. var and = ori.split("&&");
  26113. if (and.length > 1) {
  26114. for (var j = 0; j < and.length; ++j) {
  26115. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  26116. if (andj !== "true" && andj !== "false") {
  26117. if (andj[0] === "!") {
  26118. result = !evaluateCallback(andj.substring(1));
  26119. }
  26120. else {
  26121. result = evaluateCallback(andj);
  26122. }
  26123. }
  26124. else {
  26125. result = andj === "true" ? true : false;
  26126. }
  26127. if (!result) {
  26128. ori = "false";
  26129. break;
  26130. }
  26131. }
  26132. }
  26133. if (result || ori === "true") {
  26134. result = true;
  26135. break;
  26136. }
  26137. // result equals false (or undefined)
  26138. if (ori !== "true" && ori !== "false") {
  26139. if (ori[0] === "!") {
  26140. result = !evaluateCallback(ori.substring(1));
  26141. }
  26142. else {
  26143. result = evaluateCallback(ori);
  26144. }
  26145. }
  26146. else {
  26147. result = ori === "true" ? true : false;
  26148. }
  26149. }
  26150. // the whole parenthesis scope is replaced by 'true' or 'false'
  26151. return result ? "true" : "false";
  26152. };
  26153. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26154. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26155. // remove whitespaces
  26156. r = r.replace(/[\s]/g, function () { return ""; });
  26157. return r.length % 2 ? "!" : "";
  26158. });
  26159. booleanString = booleanString.trim();
  26160. if (booleanString === "!true") {
  26161. booleanString = "false";
  26162. }
  26163. else if (booleanString === "!false") {
  26164. booleanString = "true";
  26165. }
  26166. return booleanString;
  26167. };
  26168. return AndOrNotEvaluator;
  26169. })();
  26170. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26171. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26172. })(BABYLON || (BABYLON = {}));
  26173. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  26174. var BABYLON;
  26175. (function (BABYLON) {
  26176. var PostProcessRenderPass = (function () {
  26177. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26178. this._enabled = true;
  26179. this._refCount = 0;
  26180. this._name = name;
  26181. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26182. this.setRenderList(renderList);
  26183. this._renderTexture.onBeforeRender = beforeRender;
  26184. this._renderTexture.onAfterRender = afterRender;
  26185. this._scene = scene;
  26186. this._renderList = renderList;
  26187. }
  26188. // private
  26189. PostProcessRenderPass.prototype._incRefCount = function () {
  26190. if (this._refCount === 0) {
  26191. this._scene.customRenderTargets.push(this._renderTexture);
  26192. }
  26193. return ++this._refCount;
  26194. };
  26195. PostProcessRenderPass.prototype._decRefCount = function () {
  26196. this._refCount--;
  26197. if (this._refCount <= 0) {
  26198. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26199. }
  26200. return this._refCount;
  26201. };
  26202. PostProcessRenderPass.prototype._update = function () {
  26203. this.setRenderList(this._renderList);
  26204. };
  26205. // public
  26206. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26207. this._renderTexture.renderList = renderList;
  26208. };
  26209. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26210. return this._renderTexture;
  26211. };
  26212. return PostProcessRenderPass;
  26213. })();
  26214. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26215. })(BABYLON || (BABYLON = {}));
  26216. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  26217. var BABYLON;
  26218. (function (BABYLON) {
  26219. var PostProcessRenderEffect = (function () {
  26220. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26221. this._engine = engine;
  26222. this._name = name;
  26223. this._singleInstance = singleInstance || true;
  26224. this._getPostProcess = getPostProcess;
  26225. this._cameras = [];
  26226. this._indicesForCamera = [];
  26227. this._postProcesses = {};
  26228. this._renderPasses = {};
  26229. this._renderEffectAsPasses = {};
  26230. }
  26231. PostProcessRenderEffect.prototype._update = function () {
  26232. for (var renderPassName in this._renderPasses) {
  26233. this._renderPasses[renderPassName]._update();
  26234. }
  26235. };
  26236. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26237. this._renderPasses[renderPass._name] = renderPass;
  26238. this._linkParameters();
  26239. };
  26240. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26241. delete this._renderPasses[renderPass._name];
  26242. this._linkParameters();
  26243. };
  26244. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26245. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26246. this._linkParameters();
  26247. };
  26248. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26249. for (var renderPassName in this._renderPasses) {
  26250. if (renderPassName === passName) {
  26251. return this._renderPasses[passName];
  26252. }
  26253. }
  26254. };
  26255. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26256. this._renderPasses = {};
  26257. this._linkParameters();
  26258. };
  26259. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26260. var cameraKey;
  26261. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26262. for (var i = 0; i < _cam.length; i++) {
  26263. var camera = _cam[i];
  26264. var cameraName = camera.name;
  26265. if (this._singleInstance) {
  26266. cameraKey = 0;
  26267. }
  26268. else {
  26269. cameraKey = cameraName;
  26270. }
  26271. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26272. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26273. if (!this._indicesForCamera[cameraName]) {
  26274. this._indicesForCamera[cameraName] = [];
  26275. }
  26276. this._indicesForCamera[cameraName].push(index);
  26277. if (this._cameras.indexOf(camera) === -1) {
  26278. this._cameras[cameraName] = camera;
  26279. }
  26280. for (var passName in this._renderPasses) {
  26281. this._renderPasses[passName]._incRefCount();
  26282. }
  26283. }
  26284. this._linkParameters();
  26285. };
  26286. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26287. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26288. for (var i = 0; i < _cam.length; i++) {
  26289. var camera = _cam[i];
  26290. var cameraName = camera.name;
  26291. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26292. var index = this._cameras.indexOf(cameraName);
  26293. this._indicesForCamera.splice(index, 1);
  26294. this._cameras.splice(index, 1);
  26295. for (var passName in this._renderPasses) {
  26296. this._renderPasses[passName]._decRefCount();
  26297. }
  26298. }
  26299. };
  26300. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26301. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26302. for (var i = 0; i < _cam.length; i++) {
  26303. var camera = _cam[i];
  26304. var cameraName = camera.name;
  26305. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26306. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26307. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26308. }
  26309. }
  26310. for (var passName in this._renderPasses) {
  26311. this._renderPasses[passName]._incRefCount();
  26312. }
  26313. }
  26314. };
  26315. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26316. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26317. for (var i = 0; i < _cam.length; i++) {
  26318. var camera = _cam[i];
  26319. var cameraName = camera.Name;
  26320. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26321. for (var passName in this._renderPasses) {
  26322. this._renderPasses[passName]._decRefCount();
  26323. }
  26324. }
  26325. };
  26326. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26327. if (this._singleInstance) {
  26328. return this._postProcesses[0];
  26329. }
  26330. else {
  26331. return this._postProcesses[camera.name];
  26332. }
  26333. };
  26334. PostProcessRenderEffect.prototype._linkParameters = function () {
  26335. var _this = this;
  26336. for (var index in this._postProcesses) {
  26337. if (this.applyParameters) {
  26338. this.applyParameters(this._postProcesses[index]);
  26339. }
  26340. this._postProcesses[index].onBeforeRender = function (effect) {
  26341. _this._linkTextures(effect);
  26342. };
  26343. }
  26344. };
  26345. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26346. for (var renderPassName in this._renderPasses) {
  26347. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26348. }
  26349. for (var renderEffectName in this._renderEffectAsPasses) {
  26350. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26351. }
  26352. };
  26353. return PostProcessRenderEffect;
  26354. })();
  26355. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26356. })(BABYLON || (BABYLON = {}));
  26357. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  26358. var BABYLON;
  26359. (function (BABYLON) {
  26360. var PostProcessRenderPipeline = (function () {
  26361. function PostProcessRenderPipeline(engine, name) {
  26362. this._engine = engine;
  26363. this._name = name;
  26364. this._renderEffects = {};
  26365. this._renderEffectsForIsolatedPass = {};
  26366. this._cameras = [];
  26367. }
  26368. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26369. this._renderEffects[renderEffect._name] = renderEffect;
  26370. };
  26371. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26372. var renderEffects = this._renderEffects[renderEffectName];
  26373. if (!renderEffects) {
  26374. return;
  26375. }
  26376. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26377. };
  26378. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26379. var renderEffects = this._renderEffects[renderEffectName];
  26380. if (!renderEffects) {
  26381. return;
  26382. }
  26383. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26384. };
  26385. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26386. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26387. var indicesToDelete = [];
  26388. for (var i = 0; i < _cam.length; i++) {
  26389. var camera = _cam[i];
  26390. var cameraName = camera.name;
  26391. if (this._cameras.indexOf(camera) === -1) {
  26392. this._cameras[cameraName] = camera;
  26393. }
  26394. else if (unique) {
  26395. indicesToDelete.push(i);
  26396. }
  26397. }
  26398. for (var i = 0; i < indicesToDelete.length; i++) {
  26399. cameras.splice(indicesToDelete[i], 1);
  26400. }
  26401. for (var renderEffectName in this._renderEffects) {
  26402. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26403. }
  26404. };
  26405. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26406. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26407. for (var renderEffectName in this._renderEffects) {
  26408. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26409. }
  26410. for (var i = 0; i < _cam.length; i++) {
  26411. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26412. }
  26413. };
  26414. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26415. var _this = this;
  26416. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26417. var pass = null;
  26418. for (var renderEffectName in this._renderEffects) {
  26419. pass = this._renderEffects[renderEffectName].getPass(passName);
  26420. if (pass != null) {
  26421. break;
  26422. }
  26423. }
  26424. if (pass === null) {
  26425. return;
  26426. }
  26427. for (var renderEffectName in this._renderEffects) {
  26428. this._renderEffects[renderEffectName]._disable(_cam);
  26429. }
  26430. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26431. for (var i = 0; i < _cam.length; i++) {
  26432. var camera = _cam[i];
  26433. var cameraName = camera.name;
  26434. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  26435. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26436. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26437. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26438. }
  26439. };
  26440. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26441. var _this = this;
  26442. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26443. for (var i = 0; i < _cam.length; i++) {
  26444. var camera = _cam[i];
  26445. var cameraName = camera.name;
  26446. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  26447. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26448. }
  26449. for (var renderEffectName in this._renderEffects) {
  26450. this._renderEffects[renderEffectName]._enable(_cam);
  26451. }
  26452. };
  26453. PostProcessRenderPipeline.prototype._update = function () {
  26454. for (var renderEffectName in this._renderEffects) {
  26455. this._renderEffects[renderEffectName]._update();
  26456. }
  26457. for (var i = 0; i < this._cameras.length; i++) {
  26458. var cameraName = this._cameras[i].name;
  26459. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26460. this._renderEffectsForIsolatedPass[cameraName]._update();
  26461. }
  26462. }
  26463. };
  26464. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26465. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26466. return PostProcessRenderPipeline;
  26467. })();
  26468. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26469. })(BABYLON || (BABYLON = {}));
  26470. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  26471. var BABYLON;
  26472. (function (BABYLON) {
  26473. var PostProcessRenderPipelineManager = (function () {
  26474. function PostProcessRenderPipelineManager() {
  26475. this._renderPipelines = {};
  26476. }
  26477. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26478. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26479. };
  26480. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26481. var renderPipeline = this._renderPipelines[renderPipelineName];
  26482. if (!renderPipeline) {
  26483. return;
  26484. }
  26485. renderPipeline._attachCameras(cameras, unique);
  26486. };
  26487. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26488. var renderPipeline = this._renderPipelines[renderPipelineName];
  26489. if (!renderPipeline) {
  26490. return;
  26491. }
  26492. renderPipeline._detachCameras(cameras);
  26493. };
  26494. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26495. var renderPipeline = this._renderPipelines[renderPipelineName];
  26496. if (!renderPipeline) {
  26497. return;
  26498. }
  26499. renderPipeline._enableEffect(renderEffectName, cameras);
  26500. };
  26501. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26502. var renderPipeline = this._renderPipelines[renderPipelineName];
  26503. if (!renderPipeline) {
  26504. return;
  26505. }
  26506. renderPipeline._disableEffect(renderEffectName, cameras);
  26507. };
  26508. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26509. var renderPipeline = this._renderPipelines[renderPipelineName];
  26510. if (!renderPipeline) {
  26511. return;
  26512. }
  26513. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26514. };
  26515. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26516. var renderPipeline = this._renderPipelines[renderPipelineName];
  26517. if (!renderPipeline) {
  26518. return;
  26519. }
  26520. renderPipeline._disableDisplayOnlyPass(cameras);
  26521. };
  26522. PostProcessRenderPipelineManager.prototype.update = function () {
  26523. for (var renderPipelineName in this._renderPipelines) {
  26524. this._renderPipelines[renderPipelineName]._update();
  26525. }
  26526. };
  26527. return PostProcessRenderPipelineManager;
  26528. })();
  26529. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26530. })(BABYLON || (BABYLON = {}));
  26531. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  26532. var __extends = this.__extends || function (d, b) {
  26533. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26534. function __() { this.constructor = d; }
  26535. __.prototype = b.prototype;
  26536. d.prototype = new __();
  26537. };
  26538. var BABYLON;
  26539. (function (BABYLON) {
  26540. var DisplayPassPostProcess = (function (_super) {
  26541. __extends(DisplayPassPostProcess, _super);
  26542. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26543. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  26544. }
  26545. return DisplayPassPostProcess;
  26546. })(BABYLON.PostProcess);
  26547. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  26548. })(BABYLON || (BABYLON = {}));
  26549. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  26550. var BABYLON;
  26551. (function (BABYLON) {
  26552. var BoundingBoxRenderer = (function () {
  26553. function BoundingBoxRenderer(scene) {
  26554. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26555. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26556. this.showBackLines = true;
  26557. this.renderList = new BABYLON.SmartArray(32);
  26558. this._scene = scene;
  26559. }
  26560. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26561. if (this._colorShader) {
  26562. return;
  26563. }
  26564. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26565. attributes: ["position"],
  26566. uniforms: ["worldViewProjection", "color"]
  26567. });
  26568. var engine = this._scene.getEngine();
  26569. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26570. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26571. 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]);
  26572. };
  26573. BoundingBoxRenderer.prototype.reset = function () {
  26574. this.renderList.reset();
  26575. };
  26576. BoundingBoxRenderer.prototype.render = function () {
  26577. if (this.renderList.length === 0) {
  26578. return;
  26579. }
  26580. this._prepareRessources();
  26581. if (!this._colorShader.isReady()) {
  26582. return;
  26583. }
  26584. var engine = this._scene.getEngine();
  26585. engine.setDepthWrite(false);
  26586. this._colorShader._preBind();
  26587. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26588. var boundingBox = this.renderList.data[boundingBoxIndex];
  26589. var min = boundingBox.minimum;
  26590. var max = boundingBox.maximum;
  26591. var diff = max.subtract(min);
  26592. var median = min.add(diff.scale(0.5));
  26593. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26594. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26595. .multiply(boundingBox.getWorldMatrix());
  26596. // VBOs
  26597. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26598. if (this.showBackLines) {
  26599. // Back
  26600. engine.setDepthFunctionToGreaterOrEqual();
  26601. this._scene.resetCachedMaterial();
  26602. this._colorShader.setColor4("color", this.backColor.toColor4());
  26603. this._colorShader.bind(worldMatrix);
  26604. // Draw order
  26605. engine.draw(false, 0, 24);
  26606. }
  26607. // Front
  26608. engine.setDepthFunctionToLess();
  26609. this._scene.resetCachedMaterial();
  26610. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26611. this._colorShader.bind(worldMatrix);
  26612. // Draw order
  26613. engine.draw(false, 0, 24);
  26614. }
  26615. this._colorShader.unbind();
  26616. engine.setDepthFunctionToLessOrEqual();
  26617. engine.setDepthWrite(true);
  26618. };
  26619. BoundingBoxRenderer.prototype.dispose = function () {
  26620. if (!this._colorShader) {
  26621. return;
  26622. }
  26623. this._colorShader.dispose();
  26624. this._vb.dispose();
  26625. this._scene.getEngine()._releaseBuffer(this._ib);
  26626. };
  26627. return BoundingBoxRenderer;
  26628. })();
  26629. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26630. })(BABYLON || (BABYLON = {}));
  26631. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  26632. var __extends = this.__extends || function (d, b) {
  26633. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26634. function __() { this.constructor = d; }
  26635. __.prototype = b.prototype;
  26636. d.prototype = new __();
  26637. };
  26638. var BABYLON;
  26639. (function (BABYLON) {
  26640. var Condition = (function () {
  26641. function Condition(actionManager) {
  26642. this._actionManager = actionManager;
  26643. }
  26644. Condition.prototype.isValid = function () {
  26645. return true;
  26646. };
  26647. Condition.prototype._getProperty = function (propertyPath) {
  26648. return this._actionManager._getProperty(propertyPath);
  26649. };
  26650. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26651. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26652. };
  26653. return Condition;
  26654. })();
  26655. BABYLON.Condition = Condition;
  26656. var ValueCondition = (function (_super) {
  26657. __extends(ValueCondition, _super);
  26658. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26659. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26660. _super.call(this, actionManager);
  26661. this.propertyPath = propertyPath;
  26662. this.value = value;
  26663. this.operator = operator;
  26664. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26665. this._property = this._getProperty(this.propertyPath);
  26666. }
  26667. Object.defineProperty(ValueCondition, "IsEqual", {
  26668. get: function () {
  26669. return ValueCondition._IsEqual;
  26670. },
  26671. enumerable: true,
  26672. configurable: true
  26673. });
  26674. Object.defineProperty(ValueCondition, "IsDifferent", {
  26675. get: function () {
  26676. return ValueCondition._IsDifferent;
  26677. },
  26678. enumerable: true,
  26679. configurable: true
  26680. });
  26681. Object.defineProperty(ValueCondition, "IsGreater", {
  26682. get: function () {
  26683. return ValueCondition._IsGreater;
  26684. },
  26685. enumerable: true,
  26686. configurable: true
  26687. });
  26688. Object.defineProperty(ValueCondition, "IsLesser", {
  26689. get: function () {
  26690. return ValueCondition._IsLesser;
  26691. },
  26692. enumerable: true,
  26693. configurable: true
  26694. });
  26695. // Methods
  26696. ValueCondition.prototype.isValid = function () {
  26697. switch (this.operator) {
  26698. case ValueCondition.IsGreater:
  26699. return this._target[this._property] > this.value;
  26700. case ValueCondition.IsLesser:
  26701. return this._target[this._property] < this.value;
  26702. case ValueCondition.IsEqual:
  26703. case ValueCondition.IsDifferent:
  26704. var check;
  26705. if (this.value.equals) {
  26706. check = this.value.equals(this._target[this._property]);
  26707. }
  26708. else {
  26709. check = this.value === this._target[this._property];
  26710. }
  26711. return this.operator === ValueCondition.IsEqual ? check : !check;
  26712. }
  26713. return false;
  26714. };
  26715. // Statics
  26716. ValueCondition._IsEqual = 0;
  26717. ValueCondition._IsDifferent = 1;
  26718. ValueCondition._IsGreater = 2;
  26719. ValueCondition._IsLesser = 3;
  26720. return ValueCondition;
  26721. })(Condition);
  26722. BABYLON.ValueCondition = ValueCondition;
  26723. var PredicateCondition = (function (_super) {
  26724. __extends(PredicateCondition, _super);
  26725. function PredicateCondition(actionManager, predicate) {
  26726. _super.call(this, actionManager);
  26727. this.predicate = predicate;
  26728. }
  26729. PredicateCondition.prototype.isValid = function () {
  26730. return this.predicate();
  26731. };
  26732. return PredicateCondition;
  26733. })(Condition);
  26734. BABYLON.PredicateCondition = PredicateCondition;
  26735. var StateCondition = (function (_super) {
  26736. __extends(StateCondition, _super);
  26737. function StateCondition(actionManager, target, value) {
  26738. _super.call(this, actionManager);
  26739. this.value = value;
  26740. this._target = target;
  26741. }
  26742. // Methods
  26743. StateCondition.prototype.isValid = function () {
  26744. return this._target.state === this.value;
  26745. };
  26746. return StateCondition;
  26747. })(Condition);
  26748. BABYLON.StateCondition = StateCondition;
  26749. })(BABYLON || (BABYLON = {}));
  26750. //# sourceMappingURL=babylon.condition.js.map
  26751. var BABYLON;
  26752. (function (BABYLON) {
  26753. var Action = (function () {
  26754. function Action(triggerOptions, condition) {
  26755. this.triggerOptions = triggerOptions;
  26756. if (triggerOptions.parameter) {
  26757. this.trigger = triggerOptions.trigger;
  26758. this._triggerParameter = triggerOptions.parameter;
  26759. }
  26760. else {
  26761. this.trigger = triggerOptions;
  26762. }
  26763. this._nextActiveAction = this;
  26764. this._condition = condition;
  26765. }
  26766. // Methods
  26767. Action.prototype._prepare = function () {
  26768. };
  26769. Action.prototype.getTriggerParameter = function () {
  26770. return this._triggerParameter;
  26771. };
  26772. Action.prototype._executeCurrent = function (evt) {
  26773. if (this._nextActiveAction._condition) {
  26774. var condition = this._nextActiveAction._condition;
  26775. var currentRenderId = this._actionManager.getScene().getRenderId();
  26776. // We cache the current evaluation for the current frame
  26777. if (condition._evaluationId === currentRenderId) {
  26778. if (!condition._currentResult) {
  26779. return;
  26780. }
  26781. }
  26782. else {
  26783. condition._evaluationId = currentRenderId;
  26784. if (!condition.isValid()) {
  26785. condition._currentResult = false;
  26786. return;
  26787. }
  26788. condition._currentResult = true;
  26789. }
  26790. }
  26791. this._nextActiveAction.execute(evt);
  26792. if (this._nextActiveAction._child) {
  26793. if (!this._nextActiveAction._child._actionManager) {
  26794. this._nextActiveAction._child._actionManager = this._actionManager;
  26795. }
  26796. this._nextActiveAction = this._nextActiveAction._child;
  26797. }
  26798. else {
  26799. this._nextActiveAction = this;
  26800. }
  26801. };
  26802. Action.prototype.execute = function (evt) {
  26803. };
  26804. Action.prototype.then = function (action) {
  26805. this._child = action;
  26806. action._actionManager = this._actionManager;
  26807. action._prepare();
  26808. return action;
  26809. };
  26810. Action.prototype._getProperty = function (propertyPath) {
  26811. return this._actionManager._getProperty(propertyPath);
  26812. };
  26813. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26814. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26815. };
  26816. return Action;
  26817. })();
  26818. BABYLON.Action = Action;
  26819. })(BABYLON || (BABYLON = {}));
  26820. //# sourceMappingURL=babylon.action.js.map
  26821. var BABYLON;
  26822. (function (BABYLON) {
  26823. /**
  26824. * ActionEvent is the event beint sent when an action is triggered.
  26825. */
  26826. var ActionEvent = (function () {
  26827. /**
  26828. * @constructor
  26829. * @param source The mesh that triggered the action.
  26830. * @param pointerX the X mouse cursor position at the time of the event
  26831. * @param pointerY the Y mouse cursor position at the time of the event
  26832. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26833. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26834. */
  26835. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  26836. this.source = source;
  26837. this.pointerX = pointerX;
  26838. this.pointerY = pointerY;
  26839. this.meshUnderPointer = meshUnderPointer;
  26840. this.sourceEvent = sourceEvent;
  26841. }
  26842. /**
  26843. * Helper function to auto-create an ActionEvent from a source mesh.
  26844. * @param source the source mesh that triggered the event
  26845. * @param evt {Event} The original (browser) event
  26846. */
  26847. ActionEvent.CreateNew = function (source, evt) {
  26848. var scene = source.getScene();
  26849. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26850. };
  26851. /**
  26852. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26853. * @param scene the scene where the event occurred
  26854. * @param evt {Event} The original (browser) event
  26855. */
  26856. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26857. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26858. };
  26859. return ActionEvent;
  26860. })();
  26861. BABYLON.ActionEvent = ActionEvent;
  26862. /**
  26863. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26864. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26865. */
  26866. var ActionManager = (function () {
  26867. function ActionManager(scene) {
  26868. // Members
  26869. this.actions = new Array();
  26870. this._scene = scene;
  26871. scene._actionManagers.push(this);
  26872. }
  26873. Object.defineProperty(ActionManager, "NothingTrigger", {
  26874. get: function () {
  26875. return ActionManager._NothingTrigger;
  26876. },
  26877. enumerable: true,
  26878. configurable: true
  26879. });
  26880. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26881. get: function () {
  26882. return ActionManager._OnPickTrigger;
  26883. },
  26884. enumerable: true,
  26885. configurable: true
  26886. });
  26887. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26888. get: function () {
  26889. return ActionManager._OnLeftPickTrigger;
  26890. },
  26891. enumerable: true,
  26892. configurable: true
  26893. });
  26894. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26895. get: function () {
  26896. return ActionManager._OnRightPickTrigger;
  26897. },
  26898. enumerable: true,
  26899. configurable: true
  26900. });
  26901. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26902. get: function () {
  26903. return ActionManager._OnCenterPickTrigger;
  26904. },
  26905. enumerable: true,
  26906. configurable: true
  26907. });
  26908. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26909. get: function () {
  26910. return ActionManager._OnPointerOverTrigger;
  26911. },
  26912. enumerable: true,
  26913. configurable: true
  26914. });
  26915. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26916. get: function () {
  26917. return ActionManager._OnPointerOutTrigger;
  26918. },
  26919. enumerable: true,
  26920. configurable: true
  26921. });
  26922. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26923. get: function () {
  26924. return ActionManager._OnEveryFrameTrigger;
  26925. },
  26926. enumerable: true,
  26927. configurable: true
  26928. });
  26929. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26930. get: function () {
  26931. return ActionManager._OnIntersectionEnterTrigger;
  26932. },
  26933. enumerable: true,
  26934. configurable: true
  26935. });
  26936. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26937. get: function () {
  26938. return ActionManager._OnIntersectionExitTrigger;
  26939. },
  26940. enumerable: true,
  26941. configurable: true
  26942. });
  26943. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26944. get: function () {
  26945. return ActionManager._OnKeyDownTrigger;
  26946. },
  26947. enumerable: true,
  26948. configurable: true
  26949. });
  26950. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26951. get: function () {
  26952. return ActionManager._OnKeyUpTrigger;
  26953. },
  26954. enumerable: true,
  26955. configurable: true
  26956. });
  26957. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26958. get: function () {
  26959. return ActionManager._OnPickUpTrigger;
  26960. },
  26961. enumerable: true,
  26962. configurable: true
  26963. });
  26964. // Methods
  26965. ActionManager.prototype.dispose = function () {
  26966. var index = this._scene._actionManagers.indexOf(this);
  26967. if (index > -1) {
  26968. this._scene._actionManagers.splice(index, 1);
  26969. }
  26970. };
  26971. ActionManager.prototype.getScene = function () {
  26972. return this._scene;
  26973. };
  26974. /**
  26975. * Does this action manager handles actions of any of the given triggers
  26976. * @param {number[]} triggers - the triggers to be tested
  26977. * @return {boolean} whether one (or more) of the triggers is handeled
  26978. */
  26979. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26980. for (var index = 0; index < this.actions.length; index++) {
  26981. var action = this.actions[index];
  26982. if (triggers.indexOf(action.trigger) > -1) {
  26983. return true;
  26984. }
  26985. }
  26986. return false;
  26987. };
  26988. /**
  26989. * Does this action manager handles actions of a given trigger
  26990. * @param {number} trigger - the trigger to be tested
  26991. * @return {boolean} whether the trigger is handeled
  26992. */
  26993. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26994. for (var index = 0; index < this.actions.length; index++) {
  26995. var action = this.actions[index];
  26996. if (action.trigger === trigger) {
  26997. return true;
  26998. }
  26999. }
  27000. return false;
  27001. };
  27002. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  27003. /**
  27004. * Does this action manager has pointer triggers
  27005. * @return {boolean} whether or not it has pointer triggers
  27006. */
  27007. get: function () {
  27008. for (var index = 0; index < this.actions.length; index++) {
  27009. var action = this.actions[index];
  27010. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  27011. return true;
  27012. }
  27013. if (action.trigger == ActionManager._OnPickUpTrigger) {
  27014. return true;
  27015. }
  27016. }
  27017. return false;
  27018. },
  27019. enumerable: true,
  27020. configurable: true
  27021. });
  27022. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  27023. /**
  27024. * Does this action manager has pick triggers
  27025. * @return {boolean} whether or not it has pick triggers
  27026. */
  27027. get: function () {
  27028. for (var index = 0; index < this.actions.length; index++) {
  27029. var action = this.actions[index];
  27030. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  27031. return true;
  27032. }
  27033. }
  27034. return false;
  27035. },
  27036. enumerable: true,
  27037. configurable: true
  27038. });
  27039. /**
  27040. * Registers an action to this action manager
  27041. * @param {BABYLON.Action} action - the action to be registered
  27042. * @return {BABYLON.Action} the action amended (prepared) after registration
  27043. */
  27044. ActionManager.prototype.registerAction = function (action) {
  27045. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  27046. if (this.getScene().actionManager !== this) {
  27047. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  27048. return null;
  27049. }
  27050. }
  27051. this.actions.push(action);
  27052. action._actionManager = this;
  27053. action._prepare();
  27054. return action;
  27055. };
  27056. /**
  27057. * Process a specific trigger
  27058. * @param {number} trigger - the trigger to process
  27059. * @param evt {BABYLON.ActionEvent} the event details to be processed
  27060. */
  27061. ActionManager.prototype.processTrigger = function (trigger, evt) {
  27062. for (var index = 0; index < this.actions.length; index++) {
  27063. var action = this.actions[index];
  27064. if (action.trigger === trigger) {
  27065. if (trigger === ActionManager.OnKeyUpTrigger
  27066. || trigger === ActionManager.OnKeyDownTrigger) {
  27067. var parameter = action.getTriggerParameter();
  27068. if (parameter) {
  27069. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  27070. var actualkey = String.fromCharCode(unicode).toLowerCase();
  27071. if (actualkey !== parameter.toLowerCase()) {
  27072. continue;
  27073. }
  27074. }
  27075. }
  27076. action._executeCurrent(evt);
  27077. }
  27078. }
  27079. };
  27080. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  27081. var properties = propertyPath.split(".");
  27082. for (var index = 0; index < properties.length - 1; index++) {
  27083. target = target[properties[index]];
  27084. }
  27085. return target;
  27086. };
  27087. ActionManager.prototype._getProperty = function (propertyPath) {
  27088. var properties = propertyPath.split(".");
  27089. return properties[properties.length - 1];
  27090. };
  27091. // Statics
  27092. ActionManager._NothingTrigger = 0;
  27093. ActionManager._OnPickTrigger = 1;
  27094. ActionManager._OnLeftPickTrigger = 2;
  27095. ActionManager._OnRightPickTrigger = 3;
  27096. ActionManager._OnCenterPickTrigger = 4;
  27097. ActionManager._OnPointerOverTrigger = 5;
  27098. ActionManager._OnPointerOutTrigger = 6;
  27099. ActionManager._OnEveryFrameTrigger = 7;
  27100. ActionManager._OnIntersectionEnterTrigger = 8;
  27101. ActionManager._OnIntersectionExitTrigger = 9;
  27102. ActionManager._OnKeyDownTrigger = 10;
  27103. ActionManager._OnKeyUpTrigger = 11;
  27104. ActionManager._OnPickUpTrigger = 12;
  27105. return ActionManager;
  27106. })();
  27107. BABYLON.ActionManager = ActionManager;
  27108. })(BABYLON || (BABYLON = {}));
  27109. //# sourceMappingURL=babylon.actionManager.js.map
  27110. var __extends = this.__extends || function (d, b) {
  27111. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27112. function __() { this.constructor = d; }
  27113. __.prototype = b.prototype;
  27114. d.prototype = new __();
  27115. };
  27116. var BABYLON;
  27117. (function (BABYLON) {
  27118. var InterpolateValueAction = (function (_super) {
  27119. __extends(InterpolateValueAction, _super);
  27120. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  27121. if (duration === void 0) { duration = 1000; }
  27122. _super.call(this, triggerOptions, condition);
  27123. this.propertyPath = propertyPath;
  27124. this.value = value;
  27125. this.duration = duration;
  27126. this.stopOtherAnimations = stopOtherAnimations;
  27127. this._target = target;
  27128. }
  27129. InterpolateValueAction.prototype._prepare = function () {
  27130. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27131. this._property = this._getProperty(this.propertyPath);
  27132. };
  27133. InterpolateValueAction.prototype.execute = function () {
  27134. var scene = this._actionManager.getScene();
  27135. var keys = [
  27136. {
  27137. frame: 0,
  27138. value: this._target[this._property]
  27139. }, {
  27140. frame: 100,
  27141. value: this.value
  27142. }
  27143. ];
  27144. var dataType;
  27145. if (typeof this.value === "number") {
  27146. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27147. }
  27148. else if (this.value instanceof BABYLON.Color3) {
  27149. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27150. }
  27151. else if (this.value instanceof BABYLON.Vector3) {
  27152. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27153. }
  27154. else if (this.value instanceof BABYLON.Matrix) {
  27155. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27156. }
  27157. else if (this.value instanceof BABYLON.Quaternion) {
  27158. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27159. }
  27160. else {
  27161. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27162. return;
  27163. }
  27164. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27165. animation.setKeys(keys);
  27166. if (this.stopOtherAnimations) {
  27167. scene.stopAnimation(this._target);
  27168. }
  27169. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  27170. };
  27171. return InterpolateValueAction;
  27172. })(BABYLON.Action);
  27173. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27174. })(BABYLON || (BABYLON = {}));
  27175. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  27176. var __extends = this.__extends || function (d, b) {
  27177. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27178. function __() { this.constructor = d; }
  27179. __.prototype = b.prototype;
  27180. d.prototype = new __();
  27181. };
  27182. var BABYLON;
  27183. (function (BABYLON) {
  27184. var SwitchBooleanAction = (function (_super) {
  27185. __extends(SwitchBooleanAction, _super);
  27186. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27187. _super.call(this, triggerOptions, condition);
  27188. this.propertyPath = propertyPath;
  27189. this._target = target;
  27190. }
  27191. SwitchBooleanAction.prototype._prepare = function () {
  27192. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27193. this._property = this._getProperty(this.propertyPath);
  27194. };
  27195. SwitchBooleanAction.prototype.execute = function () {
  27196. this._target[this._property] = !this._target[this._property];
  27197. };
  27198. return SwitchBooleanAction;
  27199. })(BABYLON.Action);
  27200. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27201. var SetStateAction = (function (_super) {
  27202. __extends(SetStateAction, _super);
  27203. function SetStateAction(triggerOptions, target, value, condition) {
  27204. _super.call(this, triggerOptions, condition);
  27205. this.value = value;
  27206. this._target = target;
  27207. }
  27208. SetStateAction.prototype.execute = function () {
  27209. this._target.state = this.value;
  27210. };
  27211. return SetStateAction;
  27212. })(BABYLON.Action);
  27213. BABYLON.SetStateAction = SetStateAction;
  27214. var SetValueAction = (function (_super) {
  27215. __extends(SetValueAction, _super);
  27216. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27217. _super.call(this, triggerOptions, condition);
  27218. this.propertyPath = propertyPath;
  27219. this.value = value;
  27220. this._target = target;
  27221. }
  27222. SetValueAction.prototype._prepare = function () {
  27223. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27224. this._property = this._getProperty(this.propertyPath);
  27225. };
  27226. SetValueAction.prototype.execute = function () {
  27227. this._target[this._property] = this.value;
  27228. };
  27229. return SetValueAction;
  27230. })(BABYLON.Action);
  27231. BABYLON.SetValueAction = SetValueAction;
  27232. var IncrementValueAction = (function (_super) {
  27233. __extends(IncrementValueAction, _super);
  27234. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27235. _super.call(this, triggerOptions, condition);
  27236. this.propertyPath = propertyPath;
  27237. this.value = value;
  27238. this._target = target;
  27239. }
  27240. IncrementValueAction.prototype._prepare = function () {
  27241. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27242. this._property = this._getProperty(this.propertyPath);
  27243. if (typeof this._target[this._property] !== "number") {
  27244. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27245. }
  27246. };
  27247. IncrementValueAction.prototype.execute = function () {
  27248. this._target[this._property] += this.value;
  27249. };
  27250. return IncrementValueAction;
  27251. })(BABYLON.Action);
  27252. BABYLON.IncrementValueAction = IncrementValueAction;
  27253. var PlayAnimationAction = (function (_super) {
  27254. __extends(PlayAnimationAction, _super);
  27255. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27256. _super.call(this, triggerOptions, condition);
  27257. this.from = from;
  27258. this.to = to;
  27259. this.loop = loop;
  27260. this._target = target;
  27261. }
  27262. PlayAnimationAction.prototype._prepare = function () {
  27263. };
  27264. PlayAnimationAction.prototype.execute = function () {
  27265. var scene = this._actionManager.getScene();
  27266. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27267. };
  27268. return PlayAnimationAction;
  27269. })(BABYLON.Action);
  27270. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27271. var StopAnimationAction = (function (_super) {
  27272. __extends(StopAnimationAction, _super);
  27273. function StopAnimationAction(triggerOptions, target, condition) {
  27274. _super.call(this, triggerOptions, condition);
  27275. this._target = target;
  27276. }
  27277. StopAnimationAction.prototype._prepare = function () {
  27278. };
  27279. StopAnimationAction.prototype.execute = function () {
  27280. var scene = this._actionManager.getScene();
  27281. scene.stopAnimation(this._target);
  27282. };
  27283. return StopAnimationAction;
  27284. })(BABYLON.Action);
  27285. BABYLON.StopAnimationAction = StopAnimationAction;
  27286. var DoNothingAction = (function (_super) {
  27287. __extends(DoNothingAction, _super);
  27288. function DoNothingAction(triggerOptions, condition) {
  27289. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27290. _super.call(this, triggerOptions, condition);
  27291. }
  27292. DoNothingAction.prototype.execute = function () {
  27293. };
  27294. return DoNothingAction;
  27295. })(BABYLON.Action);
  27296. BABYLON.DoNothingAction = DoNothingAction;
  27297. var CombineAction = (function (_super) {
  27298. __extends(CombineAction, _super);
  27299. function CombineAction(triggerOptions, children, condition) {
  27300. _super.call(this, triggerOptions, condition);
  27301. this.children = children;
  27302. }
  27303. CombineAction.prototype._prepare = function () {
  27304. for (var index = 0; index < this.children.length; index++) {
  27305. this.children[index]._actionManager = this._actionManager;
  27306. this.children[index]._prepare();
  27307. }
  27308. };
  27309. CombineAction.prototype.execute = function (evt) {
  27310. for (var index = 0; index < this.children.length; index++) {
  27311. this.children[index].execute(evt);
  27312. }
  27313. };
  27314. return CombineAction;
  27315. })(BABYLON.Action);
  27316. BABYLON.CombineAction = CombineAction;
  27317. var ExecuteCodeAction = (function (_super) {
  27318. __extends(ExecuteCodeAction, _super);
  27319. function ExecuteCodeAction(triggerOptions, func, condition) {
  27320. _super.call(this, triggerOptions, condition);
  27321. this.func = func;
  27322. }
  27323. ExecuteCodeAction.prototype.execute = function (evt) {
  27324. this.func(evt);
  27325. };
  27326. return ExecuteCodeAction;
  27327. })(BABYLON.Action);
  27328. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27329. var SetParentAction = (function (_super) {
  27330. __extends(SetParentAction, _super);
  27331. function SetParentAction(triggerOptions, target, parent, condition) {
  27332. _super.call(this, triggerOptions, condition);
  27333. this._target = target;
  27334. this._parent = parent;
  27335. }
  27336. SetParentAction.prototype._prepare = function () {
  27337. };
  27338. SetParentAction.prototype.execute = function () {
  27339. if (this._target.parent === this._parent) {
  27340. return;
  27341. }
  27342. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27343. invertParentWorldMatrix.invert();
  27344. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27345. this._target.parent = this._parent;
  27346. };
  27347. return SetParentAction;
  27348. })(BABYLON.Action);
  27349. BABYLON.SetParentAction = SetParentAction;
  27350. var PlaySoundAction = (function (_super) {
  27351. __extends(PlaySoundAction, _super);
  27352. function PlaySoundAction(triggerOptions, sound, condition) {
  27353. _super.call(this, triggerOptions, condition);
  27354. this._sound = sound;
  27355. }
  27356. PlaySoundAction.prototype._prepare = function () {
  27357. };
  27358. PlaySoundAction.prototype.execute = function () {
  27359. if (this._sound !== undefined)
  27360. this._sound.play();
  27361. };
  27362. return PlaySoundAction;
  27363. })(BABYLON.Action);
  27364. BABYLON.PlaySoundAction = PlaySoundAction;
  27365. var StopSoundAction = (function (_super) {
  27366. __extends(StopSoundAction, _super);
  27367. function StopSoundAction(triggerOptions, sound, condition) {
  27368. _super.call(this, triggerOptions, condition);
  27369. this._sound = sound;
  27370. }
  27371. StopSoundAction.prototype._prepare = function () {
  27372. };
  27373. StopSoundAction.prototype.execute = function () {
  27374. if (this._sound !== undefined)
  27375. this._sound.stop();
  27376. };
  27377. return StopSoundAction;
  27378. })(BABYLON.Action);
  27379. BABYLON.StopSoundAction = StopSoundAction;
  27380. })(BABYLON || (BABYLON = {}));
  27381. //# sourceMappingURL=babylon.directActions.js.map
  27382. var __extends = this.__extends || function (d, b) {
  27383. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27384. function __() { this.constructor = d; }
  27385. __.prototype = b.prototype;
  27386. d.prototype = new __();
  27387. };
  27388. var BABYLON;
  27389. (function (BABYLON) {
  27390. var Geometry = (function () {
  27391. function Geometry(id, scene, vertexData, updatable, mesh) {
  27392. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27393. this._totalVertices = 0;
  27394. this._indices = [];
  27395. this._isDisposed = false;
  27396. this.id = id;
  27397. this._engine = scene.getEngine();
  27398. this._meshes = [];
  27399. this._scene = scene;
  27400. // vertexData
  27401. if (vertexData) {
  27402. this.setAllVerticesData(vertexData, updatable);
  27403. }
  27404. else {
  27405. this._totalVertices = 0;
  27406. this._indices = [];
  27407. }
  27408. // applyToMesh
  27409. if (mesh) {
  27410. this.applyToMesh(mesh);
  27411. mesh.computeWorldMatrix(true);
  27412. }
  27413. }
  27414. Geometry.prototype.getScene = function () {
  27415. return this._scene;
  27416. };
  27417. Geometry.prototype.getEngine = function () {
  27418. return this._engine;
  27419. };
  27420. Geometry.prototype.isReady = function () {
  27421. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27422. };
  27423. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27424. vertexData.applyToGeometry(this, updatable);
  27425. this.notifyUpdate();
  27426. };
  27427. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27428. this._vertexBuffers = this._vertexBuffers || {};
  27429. if (this._vertexBuffers[kind]) {
  27430. this._vertexBuffers[kind].dispose();
  27431. }
  27432. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27433. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27434. stride = this._vertexBuffers[kind].getStrideSize();
  27435. this._totalVertices = data.length / stride;
  27436. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27437. var meshes = this._meshes;
  27438. var numOfMeshes = meshes.length;
  27439. for (var index = 0; index < numOfMeshes; index++) {
  27440. var mesh = meshes[index];
  27441. mesh._resetPointsArrayCache();
  27442. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27443. mesh._createGlobalSubMesh();
  27444. mesh.computeWorldMatrix(true);
  27445. }
  27446. }
  27447. this.notifyUpdate(kind);
  27448. };
  27449. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27450. var vertexBuffer = this.getVertexBuffer(kind);
  27451. if (!vertexBuffer) {
  27452. return;
  27453. }
  27454. vertexBuffer.updateDirectly(data, offset);
  27455. this.notifyUpdate(kind);
  27456. };
  27457. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27458. var vertexBuffer = this.getVertexBuffer(kind);
  27459. if (!vertexBuffer) {
  27460. return;
  27461. }
  27462. vertexBuffer.update(data);
  27463. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27464. var extend;
  27465. var stride = vertexBuffer.getStrideSize();
  27466. this._totalVertices = data.length / stride;
  27467. if (updateExtends) {
  27468. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27469. }
  27470. var meshes = this._meshes;
  27471. var numOfMeshes = meshes.length;
  27472. for (var index = 0; index < numOfMeshes; index++) {
  27473. var mesh = meshes[index];
  27474. mesh._resetPointsArrayCache();
  27475. if (updateExtends) {
  27476. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27477. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27478. var subMesh = mesh.subMeshes[subIndex];
  27479. subMesh.refreshBoundingInfo();
  27480. }
  27481. }
  27482. }
  27483. }
  27484. this.notifyUpdate(kind);
  27485. };
  27486. Geometry.prototype.getTotalVertices = function () {
  27487. if (!this.isReady()) {
  27488. return 0;
  27489. }
  27490. return this._totalVertices;
  27491. };
  27492. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27493. var vertexBuffer = this.getVertexBuffer(kind);
  27494. if (!vertexBuffer) {
  27495. return null;
  27496. }
  27497. var orig = vertexBuffer.getData();
  27498. if (!copyWhenShared || this._meshes.length === 1) {
  27499. return orig;
  27500. }
  27501. else {
  27502. var len = orig.length;
  27503. var copy = [];
  27504. for (var i = 0; i < len; i++) {
  27505. copy.push(orig[i]);
  27506. }
  27507. return copy;
  27508. }
  27509. };
  27510. Geometry.prototype.getVertexBuffer = function (kind) {
  27511. if (!this.isReady()) {
  27512. return null;
  27513. }
  27514. return this._vertexBuffers[kind];
  27515. };
  27516. Geometry.prototype.getVertexBuffers = function () {
  27517. if (!this.isReady()) {
  27518. return null;
  27519. }
  27520. return this._vertexBuffers;
  27521. };
  27522. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27523. if (!this._vertexBuffers) {
  27524. if (this._delayInfo) {
  27525. return this._delayInfo.indexOf(kind) !== -1;
  27526. }
  27527. return false;
  27528. }
  27529. return this._vertexBuffers[kind] !== undefined;
  27530. };
  27531. Geometry.prototype.getVerticesDataKinds = function () {
  27532. var result = [];
  27533. if (!this._vertexBuffers && this._delayInfo) {
  27534. for (var kind in this._delayInfo) {
  27535. result.push(kind);
  27536. }
  27537. }
  27538. else {
  27539. for (kind in this._vertexBuffers) {
  27540. result.push(kind);
  27541. }
  27542. }
  27543. return result;
  27544. };
  27545. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27546. if (this._indexBuffer) {
  27547. this._engine._releaseBuffer(this._indexBuffer);
  27548. }
  27549. this._indices = indices;
  27550. if (this._meshes.length !== 0 && this._indices) {
  27551. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27552. }
  27553. if (totalVertices !== undefined) {
  27554. this._totalVertices = totalVertices;
  27555. }
  27556. var meshes = this._meshes;
  27557. var numOfMeshes = meshes.length;
  27558. for (var index = 0; index < numOfMeshes; index++) {
  27559. meshes[index]._createGlobalSubMesh();
  27560. }
  27561. this.notifyUpdate();
  27562. };
  27563. Geometry.prototype.getTotalIndices = function () {
  27564. if (!this.isReady()) {
  27565. return 0;
  27566. }
  27567. return this._indices.length;
  27568. };
  27569. Geometry.prototype.getIndices = function (copyWhenShared) {
  27570. if (!this.isReady()) {
  27571. return null;
  27572. }
  27573. var orig = this._indices;
  27574. if (!copyWhenShared || this._meshes.length === 1) {
  27575. return orig;
  27576. }
  27577. else {
  27578. var len = orig.length;
  27579. var copy = [];
  27580. for (var i = 0; i < len; i++) {
  27581. copy.push(orig[i]);
  27582. }
  27583. return copy;
  27584. }
  27585. };
  27586. Geometry.prototype.getIndexBuffer = function () {
  27587. if (!this.isReady()) {
  27588. return null;
  27589. }
  27590. return this._indexBuffer;
  27591. };
  27592. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27593. var meshes = this._meshes;
  27594. var index = meshes.indexOf(mesh);
  27595. if (index === -1) {
  27596. return;
  27597. }
  27598. for (var kind in this._vertexBuffers) {
  27599. this._vertexBuffers[kind].dispose();
  27600. }
  27601. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27602. this._indexBuffer = null;
  27603. }
  27604. meshes.splice(index, 1);
  27605. mesh._geometry = null;
  27606. if (meshes.length === 0 && shouldDispose) {
  27607. this.dispose();
  27608. }
  27609. };
  27610. Geometry.prototype.applyToMesh = function (mesh) {
  27611. if (mesh._geometry === this) {
  27612. return;
  27613. }
  27614. var previousGeometry = mesh._geometry;
  27615. if (previousGeometry) {
  27616. previousGeometry.releaseForMesh(mesh);
  27617. }
  27618. var meshes = this._meshes;
  27619. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27620. mesh._geometry = this;
  27621. this._scene.pushGeometry(this);
  27622. meshes.push(mesh);
  27623. if (this.isReady()) {
  27624. this._applyToMesh(mesh);
  27625. }
  27626. else {
  27627. mesh._boundingInfo = this._boundingInfo;
  27628. }
  27629. };
  27630. Geometry.prototype._applyToMesh = function (mesh) {
  27631. var numOfMeshes = this._meshes.length;
  27632. // vertexBuffers
  27633. for (var kind in this._vertexBuffers) {
  27634. if (numOfMeshes === 1) {
  27635. this._vertexBuffers[kind].create();
  27636. }
  27637. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27638. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27639. mesh._resetPointsArrayCache();
  27640. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27641. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27642. mesh._createGlobalSubMesh();
  27643. //bounding info was just created again, world matrix should be applied again.
  27644. mesh._updateBoundingInfo();
  27645. }
  27646. }
  27647. // indexBuffer
  27648. if (numOfMeshes === 1 && this._indices) {
  27649. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27650. }
  27651. if (this._indexBuffer) {
  27652. this._indexBuffer.references = numOfMeshes;
  27653. }
  27654. };
  27655. Geometry.prototype.notifyUpdate = function (kind) {
  27656. if (this.onGeometryUpdated) {
  27657. this.onGeometryUpdated(this, kind);
  27658. }
  27659. };
  27660. Geometry.prototype.load = function (scene, onLoaded) {
  27661. var _this = this;
  27662. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27663. return;
  27664. }
  27665. if (this.isReady()) {
  27666. if (onLoaded) {
  27667. onLoaded();
  27668. }
  27669. return;
  27670. }
  27671. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27672. scene._addPendingData(this);
  27673. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27674. _this._delayLoadingFunction(JSON.parse(data), _this);
  27675. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27676. _this._delayInfo = [];
  27677. scene._removePendingData(_this);
  27678. var meshes = _this._meshes;
  27679. var numOfMeshes = meshes.length;
  27680. for (var index = 0; index < numOfMeshes; index++) {
  27681. _this._applyToMesh(meshes[index]);
  27682. }
  27683. if (onLoaded) {
  27684. onLoaded();
  27685. }
  27686. }, function () { }, scene.database);
  27687. };
  27688. Geometry.prototype.isDisposed = function () {
  27689. return this._isDisposed;
  27690. };
  27691. Geometry.prototype.dispose = function () {
  27692. var meshes = this._meshes;
  27693. var numOfMeshes = meshes.length;
  27694. var index;
  27695. for (index = 0; index < numOfMeshes; index++) {
  27696. this.releaseForMesh(meshes[index]);
  27697. }
  27698. this._meshes = [];
  27699. for (var kind in this._vertexBuffers) {
  27700. this._vertexBuffers[kind].dispose();
  27701. }
  27702. this._vertexBuffers = [];
  27703. this._totalVertices = 0;
  27704. if (this._indexBuffer) {
  27705. this._engine._releaseBuffer(this._indexBuffer);
  27706. }
  27707. this._indexBuffer = null;
  27708. this._indices = [];
  27709. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27710. this.delayLoadingFile = null;
  27711. this._delayLoadingFunction = null;
  27712. this._delayInfo = [];
  27713. this._boundingInfo = null; // todo: .dispose()
  27714. this._scene.removeGeometry(this);
  27715. this._isDisposed = true;
  27716. };
  27717. Geometry.prototype.copy = function (id) {
  27718. var vertexData = new BABYLON.VertexData();
  27719. vertexData.indices = [];
  27720. var indices = this.getIndices();
  27721. for (var index = 0; index < indices.length; index++) {
  27722. vertexData.indices.push(indices[index]);
  27723. }
  27724. var updatable = false;
  27725. var stopChecking = false;
  27726. for (var kind in this._vertexBuffers) {
  27727. // using slice() to make a copy of the array and not just reference it
  27728. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  27729. if (!stopChecking) {
  27730. updatable = this.getVertexBuffer(kind).isUpdatable();
  27731. stopChecking = !updatable;
  27732. }
  27733. }
  27734. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27735. geometry.delayLoadState = this.delayLoadState;
  27736. geometry.delayLoadingFile = this.delayLoadingFile;
  27737. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27738. for (kind in this._delayInfo) {
  27739. geometry._delayInfo = geometry._delayInfo || [];
  27740. geometry._delayInfo.push(kind);
  27741. }
  27742. // Bounding info
  27743. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  27744. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27745. return geometry;
  27746. };
  27747. // Statics
  27748. Geometry.ExtractFromMesh = function (mesh, id) {
  27749. var geometry = mesh._geometry;
  27750. if (!geometry) {
  27751. return null;
  27752. }
  27753. return geometry.copy(id);
  27754. };
  27755. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27756. // be aware Math.random() could cause collisions
  27757. Geometry.RandomId = function () {
  27758. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27759. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27760. return v.toString(16);
  27761. });
  27762. };
  27763. return Geometry;
  27764. })();
  27765. BABYLON.Geometry = Geometry;
  27766. /////// Primitives //////////////////////////////////////////////
  27767. var Geometry;
  27768. (function (Geometry) {
  27769. var Primitives;
  27770. (function (Primitives) {
  27771. /// Abstract class
  27772. var _Primitive = (function (_super) {
  27773. __extends(_Primitive, _super);
  27774. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27775. this._beingRegenerated = true;
  27776. this._canBeRegenerated = canBeRegenerated;
  27777. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27778. this._beingRegenerated = false;
  27779. }
  27780. _Primitive.prototype.canBeRegenerated = function () {
  27781. return this._canBeRegenerated;
  27782. };
  27783. _Primitive.prototype.regenerate = function () {
  27784. if (!this._canBeRegenerated) {
  27785. return;
  27786. }
  27787. this._beingRegenerated = true;
  27788. this.setAllVerticesData(this._regenerateVertexData(), false);
  27789. this._beingRegenerated = false;
  27790. };
  27791. _Primitive.prototype.asNewGeometry = function (id) {
  27792. return _super.prototype.copy.call(this, id);
  27793. };
  27794. // overrides
  27795. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27796. if (!this._beingRegenerated) {
  27797. return;
  27798. }
  27799. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27800. };
  27801. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27802. if (!this._beingRegenerated) {
  27803. return;
  27804. }
  27805. _super.prototype.setVerticesData.call(this, kind, data, false);
  27806. };
  27807. // to override
  27808. // protected
  27809. _Primitive.prototype._regenerateVertexData = function () {
  27810. throw new Error("Abstract method");
  27811. };
  27812. _Primitive.prototype.copy = function (id) {
  27813. throw new Error("Must be overriden in sub-classes.");
  27814. };
  27815. return _Primitive;
  27816. })(Geometry);
  27817. Primitives._Primitive = _Primitive;
  27818. var Ribbon = (function (_super) {
  27819. __extends(Ribbon, _super);
  27820. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27821. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27822. this.pathArray = pathArray;
  27823. this.closeArray = closeArray;
  27824. this.closePath = closePath;
  27825. this.offset = offset;
  27826. this.side = side;
  27827. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27828. }
  27829. Ribbon.prototype._regenerateVertexData = function () {
  27830. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  27831. };
  27832. Ribbon.prototype.copy = function (id) {
  27833. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27834. };
  27835. return Ribbon;
  27836. })(_Primitive);
  27837. Primitives.Ribbon = Ribbon;
  27838. var Box = (function (_super) {
  27839. __extends(Box, _super);
  27840. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27841. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27842. this.size = size;
  27843. this.side = side;
  27844. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27845. }
  27846. Box.prototype._regenerateVertexData = function () {
  27847. return BABYLON.VertexData.CreateBox(this.size, this.side);
  27848. };
  27849. Box.prototype.copy = function (id) {
  27850. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27851. };
  27852. return Box;
  27853. })(_Primitive);
  27854. Primitives.Box = Box;
  27855. var Sphere = (function (_super) {
  27856. __extends(Sphere, _super);
  27857. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27858. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27859. this.segments = segments;
  27860. this.diameter = diameter;
  27861. this.side = side;
  27862. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27863. }
  27864. Sphere.prototype._regenerateVertexData = function () {
  27865. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  27866. };
  27867. Sphere.prototype.copy = function (id) {
  27868. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27869. };
  27870. return Sphere;
  27871. })(_Primitive);
  27872. Primitives.Sphere = Sphere;
  27873. var Cylinder = (function (_super) {
  27874. __extends(Cylinder, _super);
  27875. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27876. if (subdivisions === void 0) { subdivisions = 1; }
  27877. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27878. this.height = height;
  27879. this.diameterTop = diameterTop;
  27880. this.diameterBottom = diameterBottom;
  27881. this.tessellation = tessellation;
  27882. this.subdivisions = subdivisions;
  27883. this.side = side;
  27884. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27885. }
  27886. Cylinder.prototype._regenerateVertexData = function () {
  27887. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  27888. };
  27889. Cylinder.prototype.copy = function (id) {
  27890. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27891. };
  27892. return Cylinder;
  27893. })(_Primitive);
  27894. Primitives.Cylinder = Cylinder;
  27895. var Torus = (function (_super) {
  27896. __extends(Torus, _super);
  27897. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27898. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27899. this.diameter = diameter;
  27900. this.thickness = thickness;
  27901. this.tessellation = tessellation;
  27902. this.side = side;
  27903. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27904. }
  27905. Torus.prototype._regenerateVertexData = function () {
  27906. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  27907. };
  27908. Torus.prototype.copy = function (id) {
  27909. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27910. };
  27911. return Torus;
  27912. })(_Primitive);
  27913. Primitives.Torus = Torus;
  27914. var Ground = (function (_super) {
  27915. __extends(Ground, _super);
  27916. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27917. this.width = width;
  27918. this.height = height;
  27919. this.subdivisions = subdivisions;
  27920. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27921. }
  27922. Ground.prototype._regenerateVertexData = function () {
  27923. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  27924. };
  27925. Ground.prototype.copy = function (id) {
  27926. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27927. };
  27928. return Ground;
  27929. })(_Primitive);
  27930. Primitives.Ground = Ground;
  27931. var TiledGround = (function (_super) {
  27932. __extends(TiledGround, _super);
  27933. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27934. this.xmin = xmin;
  27935. this.zmin = zmin;
  27936. this.xmax = xmax;
  27937. this.zmax = zmax;
  27938. this.subdivisions = subdivisions;
  27939. this.precision = precision;
  27940. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27941. }
  27942. TiledGround.prototype._regenerateVertexData = function () {
  27943. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  27944. };
  27945. TiledGround.prototype.copy = function (id) {
  27946. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27947. };
  27948. return TiledGround;
  27949. })(_Primitive);
  27950. Primitives.TiledGround = TiledGround;
  27951. var Plane = (function (_super) {
  27952. __extends(Plane, _super);
  27953. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27954. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27955. this.size = size;
  27956. this.side = side;
  27957. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27958. }
  27959. Plane.prototype._regenerateVertexData = function () {
  27960. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  27961. };
  27962. Plane.prototype.copy = function (id) {
  27963. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27964. };
  27965. return Plane;
  27966. })(_Primitive);
  27967. Primitives.Plane = Plane;
  27968. var TorusKnot = (function (_super) {
  27969. __extends(TorusKnot, _super);
  27970. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27971. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27972. this.radius = radius;
  27973. this.tube = tube;
  27974. this.radialSegments = radialSegments;
  27975. this.tubularSegments = tubularSegments;
  27976. this.p = p;
  27977. this.q = q;
  27978. this.side = side;
  27979. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27980. }
  27981. TorusKnot.prototype._regenerateVertexData = function () {
  27982. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  27983. };
  27984. TorusKnot.prototype.copy = function (id) {
  27985. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27986. };
  27987. return TorusKnot;
  27988. })(_Primitive);
  27989. Primitives.TorusKnot = TorusKnot;
  27990. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27991. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27992. })(BABYLON || (BABYLON = {}));
  27993. //# sourceMappingURL=babylon.geometry.js.map
  27994. var __extends = this.__extends || function (d, b) {
  27995. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27996. function __() { this.constructor = d; }
  27997. __.prototype = b.prototype;
  27998. d.prototype = new __();
  27999. };
  28000. var BABYLON;
  28001. (function (BABYLON) {
  28002. var GroundMesh = (function (_super) {
  28003. __extends(GroundMesh, _super);
  28004. function GroundMesh(name, scene) {
  28005. _super.call(this, name, scene);
  28006. this.generateOctree = false;
  28007. this._worldInverse = new BABYLON.Matrix();
  28008. }
  28009. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28010. get: function () {
  28011. return this._subdivisions;
  28012. },
  28013. enumerable: true,
  28014. configurable: true
  28015. });
  28016. GroundMesh.prototype.optimize = function (chunksCount) {
  28017. this.subdivide(this._subdivisions);
  28018. this.createOrUpdateSubmeshesOctree(32);
  28019. };
  28020. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28021. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  28022. this.getWorldMatrix().invertToRef(this._worldInverse);
  28023. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  28024. var pickInfo = this.intersects(ray);
  28025. if (pickInfo.hit) {
  28026. return pickInfo.pickedPoint.y;
  28027. }
  28028. return 0;
  28029. };
  28030. return GroundMesh;
  28031. })(BABYLON.Mesh);
  28032. BABYLON.GroundMesh = GroundMesh;
  28033. })(BABYLON || (BABYLON = {}));
  28034. //# sourceMappingURL=babylon.groundMesh.js.map
  28035. var __extends = this.__extends || function (d, b) {
  28036. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28037. function __() { this.constructor = d; }
  28038. __.prototype = b.prototype;
  28039. d.prototype = new __();
  28040. };
  28041. var BABYLON;
  28042. (function (BABYLON) {
  28043. var LinesMesh = (function (_super) {
  28044. __extends(LinesMesh, _super);
  28045. function LinesMesh(name, scene, updatable) {
  28046. if (updatable === void 0) { updatable = false; }
  28047. _super.call(this, name, scene);
  28048. this.color = new BABYLON.Color3(1, 1, 1);
  28049. this.alpha = 1;
  28050. this._indices = new Array();
  28051. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28052. attributes: ["position"],
  28053. uniforms: ["worldViewProjection", "color"],
  28054. needAlphaBlending: true
  28055. });
  28056. }
  28057. Object.defineProperty(LinesMesh.prototype, "material", {
  28058. get: function () {
  28059. return this._colorShader;
  28060. },
  28061. enumerable: true,
  28062. configurable: true
  28063. });
  28064. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28065. get: function () {
  28066. return false;
  28067. },
  28068. enumerable: true,
  28069. configurable: true
  28070. });
  28071. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28072. get: function () {
  28073. return false;
  28074. },
  28075. enumerable: true,
  28076. configurable: true
  28077. });
  28078. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28079. var engine = this.getScene().getEngine();
  28080. var indexToBind = this._geometry.getIndexBuffer();
  28081. // VBOs
  28082. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28083. // Color
  28084. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28085. };
  28086. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28087. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28088. return;
  28089. }
  28090. var engine = this.getScene().getEngine();
  28091. // Draw order
  28092. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28093. };
  28094. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28095. return null;
  28096. };
  28097. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28098. this._colorShader.dispose();
  28099. _super.prototype.dispose.call(this, doNotRecurse);
  28100. };
  28101. return LinesMesh;
  28102. })(BABYLON.Mesh);
  28103. BABYLON.LinesMesh = LinesMesh;
  28104. })(BABYLON || (BABYLON = {}));
  28105. //# sourceMappingURL=babylon.linesMesh.js.map
  28106. var BABYLON;
  28107. (function (BABYLON) {
  28108. var OutlineRenderer = (function () {
  28109. function OutlineRenderer(scene) {
  28110. this._scene = scene;
  28111. }
  28112. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  28113. var _this = this;
  28114. if (useOverlay === void 0) { useOverlay = false; }
  28115. var scene = this._scene;
  28116. var engine = this._scene.getEngine();
  28117. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28118. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  28119. return;
  28120. }
  28121. var mesh = subMesh.getRenderingMesh();
  28122. var material = subMesh.getMaterial();
  28123. engine.enableEffect(this._effect);
  28124. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  28125. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  28126. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28127. // Bones
  28128. if (mesh.useBones) {
  28129. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28130. }
  28131. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  28132. // Alpha test
  28133. if (material && material.needAlphaTesting()) {
  28134. var alphaTexture = material.getAlphaTestTexture();
  28135. this._effect.setTexture("diffuseSampler", alphaTexture);
  28136. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28137. }
  28138. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  28139. };
  28140. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  28141. var defines = [];
  28142. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  28143. var mesh = subMesh.getMesh();
  28144. var material = subMesh.getMaterial();
  28145. // Alpha test
  28146. if (material && material.needAlphaTesting()) {
  28147. defines.push("#define ALPHATEST");
  28148. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28149. attribs.push(BABYLON.VertexBuffer.UVKind);
  28150. defines.push("#define UV1");
  28151. }
  28152. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28153. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28154. defines.push("#define UV2");
  28155. }
  28156. }
  28157. // Bones
  28158. if (mesh.useBones) {
  28159. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28160. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28161. defines.push("#define BONES");
  28162. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28163. }
  28164. // Instances
  28165. if (useInstances) {
  28166. defines.push("#define INSTANCES");
  28167. attribs.push("world0");
  28168. attribs.push("world1");
  28169. attribs.push("world2");
  28170. attribs.push("world3");
  28171. }
  28172. // Get correct effect
  28173. var join = defines.join("\n");
  28174. if (this._cachedDefines !== join) {
  28175. this._cachedDefines = join;
  28176. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  28177. }
  28178. return this._effect.isReady();
  28179. };
  28180. return OutlineRenderer;
  28181. })();
  28182. BABYLON.OutlineRenderer = OutlineRenderer;
  28183. })(BABYLON || (BABYLON = {}));
  28184. //# sourceMappingURL=babylon.outlineRenderer.js.map
  28185. var BABYLON;
  28186. (function (BABYLON) {
  28187. var MeshAssetTask = (function () {
  28188. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  28189. this.name = name;
  28190. this.meshesNames = meshesNames;
  28191. this.rootUrl = rootUrl;
  28192. this.sceneFilename = sceneFilename;
  28193. this.isCompleted = false;
  28194. }
  28195. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28196. var _this = this;
  28197. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  28198. _this.loadedMeshes = meshes;
  28199. _this.loadedParticleSystems = particleSystems;
  28200. _this.loadedSkeletons = skeletons;
  28201. _this.isCompleted = true;
  28202. if (_this.onSuccess) {
  28203. _this.onSuccess(_this);
  28204. }
  28205. onSuccess();
  28206. }, null, function () {
  28207. if (_this.onError) {
  28208. _this.onError(_this);
  28209. }
  28210. onError();
  28211. });
  28212. };
  28213. return MeshAssetTask;
  28214. })();
  28215. BABYLON.MeshAssetTask = MeshAssetTask;
  28216. var TextFileAssetTask = (function () {
  28217. function TextFileAssetTask(name, url) {
  28218. this.name = name;
  28219. this.url = url;
  28220. this.isCompleted = false;
  28221. }
  28222. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28223. var _this = this;
  28224. BABYLON.Tools.LoadFile(this.url, function (data) {
  28225. _this.text = data;
  28226. _this.isCompleted = true;
  28227. if (_this.onSuccess) {
  28228. _this.onSuccess(_this);
  28229. }
  28230. onSuccess();
  28231. }, null, scene.database, false, function () {
  28232. if (_this.onError) {
  28233. _this.onError(_this);
  28234. }
  28235. onError();
  28236. });
  28237. };
  28238. return TextFileAssetTask;
  28239. })();
  28240. BABYLON.TextFileAssetTask = TextFileAssetTask;
  28241. var BinaryFileAssetTask = (function () {
  28242. function BinaryFileAssetTask(name, url) {
  28243. this.name = name;
  28244. this.url = url;
  28245. this.isCompleted = false;
  28246. }
  28247. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28248. var _this = this;
  28249. BABYLON.Tools.LoadFile(this.url, function (data) {
  28250. _this.data = data;
  28251. _this.isCompleted = true;
  28252. if (_this.onSuccess) {
  28253. _this.onSuccess(_this);
  28254. }
  28255. onSuccess();
  28256. }, null, scene.database, true, function () {
  28257. if (_this.onError) {
  28258. _this.onError(_this);
  28259. }
  28260. onError();
  28261. });
  28262. };
  28263. return BinaryFileAssetTask;
  28264. })();
  28265. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  28266. var ImageAssetTask = (function () {
  28267. function ImageAssetTask(name, url) {
  28268. this.name = name;
  28269. this.url = url;
  28270. this.isCompleted = false;
  28271. }
  28272. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28273. var _this = this;
  28274. var img = new Image();
  28275. img.onload = function () {
  28276. _this.image = img;
  28277. _this.isCompleted = true;
  28278. if (_this.onSuccess) {
  28279. _this.onSuccess(_this);
  28280. }
  28281. onSuccess();
  28282. };
  28283. img.onerror = function () {
  28284. if (_this.onError) {
  28285. _this.onError(_this);
  28286. }
  28287. onError();
  28288. };
  28289. img.src = this.url;
  28290. };
  28291. return ImageAssetTask;
  28292. })();
  28293. BABYLON.ImageAssetTask = ImageAssetTask;
  28294. var TextureAssetTask = (function () {
  28295. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  28296. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28297. this.name = name;
  28298. this.url = url;
  28299. this.noMipmap = noMipmap;
  28300. this.invertY = invertY;
  28301. this.samplingMode = samplingMode;
  28302. this.isCompleted = false;
  28303. }
  28304. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28305. var _this = this;
  28306. var onload = function () {
  28307. _this.isCompleted = true;
  28308. if (_this.onSuccess) {
  28309. _this.onSuccess(_this);
  28310. }
  28311. onSuccess();
  28312. };
  28313. var onerror = function () {
  28314. if (_this.onError) {
  28315. _this.onError(_this);
  28316. }
  28317. onError();
  28318. };
  28319. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  28320. };
  28321. return TextureAssetTask;
  28322. })();
  28323. BABYLON.TextureAssetTask = TextureAssetTask;
  28324. var AssetsManager = (function () {
  28325. function AssetsManager(scene) {
  28326. this._tasks = new Array();
  28327. this._waitingTasksCount = 0;
  28328. this.useDefaultLoadingScreen = true;
  28329. this._scene = scene;
  28330. }
  28331. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  28332. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  28333. this._tasks.push(task);
  28334. return task;
  28335. };
  28336. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  28337. var task = new TextFileAssetTask(taskName, url);
  28338. this._tasks.push(task);
  28339. return task;
  28340. };
  28341. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  28342. var task = new BinaryFileAssetTask(taskName, url);
  28343. this._tasks.push(task);
  28344. return task;
  28345. };
  28346. AssetsManager.prototype.addImageTask = function (taskName, url) {
  28347. var task = new ImageAssetTask(taskName, url);
  28348. this._tasks.push(task);
  28349. return task;
  28350. };
  28351. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  28352. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28353. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  28354. this._tasks.push(task);
  28355. return task;
  28356. };
  28357. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  28358. this._waitingTasksCount--;
  28359. if (this._waitingTasksCount === 0) {
  28360. if (this.onFinish) {
  28361. this.onFinish(this._tasks);
  28362. }
  28363. this._scene.getEngine().hideLoadingUI();
  28364. }
  28365. };
  28366. AssetsManager.prototype._runTask = function (task) {
  28367. var _this = this;
  28368. task.run(this._scene, function () {
  28369. if (_this.onTaskSuccess) {
  28370. _this.onTaskSuccess(task);
  28371. }
  28372. _this._decreaseWaitingTasksCount();
  28373. }, function () {
  28374. if (_this.onTaskError) {
  28375. _this.onTaskError(task);
  28376. }
  28377. _this._decreaseWaitingTasksCount();
  28378. });
  28379. };
  28380. AssetsManager.prototype.reset = function () {
  28381. this._tasks = new Array();
  28382. return this;
  28383. };
  28384. AssetsManager.prototype.load = function () {
  28385. this._waitingTasksCount = this._tasks.length;
  28386. if (this._waitingTasksCount === 0) {
  28387. if (this.onFinish) {
  28388. this.onFinish(this._tasks);
  28389. }
  28390. return this;
  28391. }
  28392. if (this.useDefaultLoadingScreen) {
  28393. this._scene.getEngine().displayLoadingUI();
  28394. }
  28395. for (var index = 0; index < this._tasks.length; index++) {
  28396. var task = this._tasks[index];
  28397. this._runTask(task);
  28398. }
  28399. return this;
  28400. };
  28401. return AssetsManager;
  28402. })();
  28403. BABYLON.AssetsManager = AssetsManager;
  28404. })(BABYLON || (BABYLON = {}));
  28405. //# sourceMappingURL=babylon.assetsManager.js.map
  28406. var __extends = this.__extends || function (d, b) {
  28407. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28408. function __() { this.constructor = d; }
  28409. __.prototype = b.prototype;
  28410. d.prototype = new __();
  28411. };
  28412. var BABYLON;
  28413. (function (BABYLON) {
  28414. var VRDeviceOrientationFreeCamera = (function (_super) {
  28415. __extends(VRDeviceOrientationFreeCamera, _super);
  28416. function VRDeviceOrientationFreeCamera(name, position, scene) {
  28417. _super.call(this, name, position, scene);
  28418. this._alpha = 0;
  28419. this._beta = 0;
  28420. this._gamma = 0;
  28421. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR);
  28422. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  28423. }
  28424. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  28425. this._alpha = +evt.alpha | 0;
  28426. this._beta = +evt.beta | 0;
  28427. this._gamma = +evt.gamma | 0;
  28428. if (this._gamma < 0) {
  28429. this._gamma = 90 + this._gamma;
  28430. }
  28431. else {
  28432. // Incline it in the correct angle.
  28433. this._gamma = 270 - this._gamma;
  28434. }
  28435. this.rotation.x = this._gamma / 180.0 * Math.PI;
  28436. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28437. this.rotation.z = this._beta / 180.0 * Math.PI;
  28438. };
  28439. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28440. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28441. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  28442. };
  28443. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  28444. _super.prototype.detachControl.call(this, element);
  28445. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  28446. };
  28447. return VRDeviceOrientationFreeCamera;
  28448. })(BABYLON.FreeCamera);
  28449. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  28450. })(BABYLON || (BABYLON = {}));
  28451. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28452. var __extends = this.__extends || function (d, b) {
  28453. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28454. function __() { this.constructor = d; }
  28455. __.prototype = b.prototype;
  28456. d.prototype = new __();
  28457. };
  28458. var BABYLON;
  28459. (function (BABYLON) {
  28460. var WebVRFreeCamera = (function (_super) {
  28461. __extends(WebVRFreeCamera, _super);
  28462. function WebVRFreeCamera(name, position, scene) {
  28463. _super.call(this, name, position, scene);
  28464. this._hmdDevice = null;
  28465. this._sensorDevice = null;
  28466. this._cacheState = null;
  28467. this._cacheQuaternion = new BABYLON.Quaternion();
  28468. this._cacheRotation = BABYLON.Vector3.Zero();
  28469. this._vrEnabled = false;
  28470. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR);
  28471. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28472. }
  28473. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  28474. var size = devices.length;
  28475. var i = 0;
  28476. // Reset devices.
  28477. this._sensorDevice = null;
  28478. this._hmdDevice = null;
  28479. // Search for a HmdDevice.
  28480. while (i < size && this._hmdDevice === null) {
  28481. if (devices[i] instanceof HMDVRDevice) {
  28482. this._hmdDevice = devices[i];
  28483. }
  28484. i++;
  28485. }
  28486. i = 0;
  28487. while (i < size && this._sensorDevice === null) {
  28488. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28489. this._sensorDevice = devices[i];
  28490. }
  28491. i++;
  28492. }
  28493. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28494. };
  28495. WebVRFreeCamera.prototype._checkInputs = function () {
  28496. if (this._vrEnabled) {
  28497. this._cacheState = this._sensorDevice.getState();
  28498. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28499. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28500. this.rotation.x = -this._cacheRotation.z;
  28501. this.rotation.y = -this._cacheRotation.y;
  28502. this.rotation.z = this._cacheRotation.x;
  28503. }
  28504. _super.prototype._checkInputs.call(this);
  28505. };
  28506. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28507. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28508. if (navigator.getVRDevices) {
  28509. navigator.getVRDevices().then(this._getWebVRDevices);
  28510. }
  28511. else if (navigator.mozGetVRDevices) {
  28512. navigator.mozGetVRDevices(this._getWebVRDevices);
  28513. }
  28514. };
  28515. WebVRFreeCamera.prototype.detachControl = function (element) {
  28516. _super.prototype.detachControl.call(this, element);
  28517. this._vrEnabled = false;
  28518. };
  28519. return WebVRFreeCamera;
  28520. })(BABYLON.FreeCamera);
  28521. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  28522. })(BABYLON || (BABYLON = {}));
  28523. //# sourceMappingURL=babylon.webVRCamera.js.map
  28524. var __extends = this.__extends || function (d, b) {
  28525. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28526. function __() { this.constructor = d; }
  28527. __.prototype = b.prototype;
  28528. d.prototype = new __();
  28529. };
  28530. var BABYLON;
  28531. (function (BABYLON) {
  28532. // Standard optimizations
  28533. var SceneOptimization = (function () {
  28534. function SceneOptimization(priority) {
  28535. if (priority === void 0) { priority = 0; }
  28536. this.priority = priority;
  28537. this.apply = function (scene) {
  28538. return true; // Return true if everything that can be done was applied
  28539. };
  28540. }
  28541. return SceneOptimization;
  28542. })();
  28543. BABYLON.SceneOptimization = SceneOptimization;
  28544. var TextureOptimization = (function (_super) {
  28545. __extends(TextureOptimization, _super);
  28546. function TextureOptimization(priority, maximumSize) {
  28547. var _this = this;
  28548. if (priority === void 0) { priority = 0; }
  28549. if (maximumSize === void 0) { maximumSize = 1024; }
  28550. _super.call(this, priority);
  28551. this.priority = priority;
  28552. this.maximumSize = maximumSize;
  28553. this.apply = function (scene) {
  28554. var allDone = true;
  28555. for (var index = 0; index < scene.textures.length; index++) {
  28556. var texture = scene.textures[index];
  28557. if (!texture.canRescale) {
  28558. continue;
  28559. }
  28560. var currentSize = texture.getSize();
  28561. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28562. if (maxDimension > _this.maximumSize) {
  28563. texture.scale(0.5);
  28564. allDone = false;
  28565. }
  28566. }
  28567. return allDone;
  28568. };
  28569. }
  28570. return TextureOptimization;
  28571. })(SceneOptimization);
  28572. BABYLON.TextureOptimization = TextureOptimization;
  28573. var HardwareScalingOptimization = (function (_super) {
  28574. __extends(HardwareScalingOptimization, _super);
  28575. function HardwareScalingOptimization(priority, maximumScale) {
  28576. var _this = this;
  28577. if (priority === void 0) { priority = 0; }
  28578. if (maximumScale === void 0) { maximumScale = 2; }
  28579. _super.call(this, priority);
  28580. this.priority = priority;
  28581. this.maximumScale = maximumScale;
  28582. this._currentScale = 1;
  28583. this.apply = function (scene) {
  28584. _this._currentScale++;
  28585. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28586. return _this._currentScale >= _this.maximumScale;
  28587. };
  28588. }
  28589. return HardwareScalingOptimization;
  28590. })(SceneOptimization);
  28591. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28592. var ShadowsOptimization = (function (_super) {
  28593. __extends(ShadowsOptimization, _super);
  28594. function ShadowsOptimization() {
  28595. _super.apply(this, arguments);
  28596. this.apply = function (scene) {
  28597. scene.shadowsEnabled = false;
  28598. return true;
  28599. };
  28600. }
  28601. return ShadowsOptimization;
  28602. })(SceneOptimization);
  28603. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28604. var PostProcessesOptimization = (function (_super) {
  28605. __extends(PostProcessesOptimization, _super);
  28606. function PostProcessesOptimization() {
  28607. _super.apply(this, arguments);
  28608. this.apply = function (scene) {
  28609. scene.postProcessesEnabled = false;
  28610. return true;
  28611. };
  28612. }
  28613. return PostProcessesOptimization;
  28614. })(SceneOptimization);
  28615. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28616. var LensFlaresOptimization = (function (_super) {
  28617. __extends(LensFlaresOptimization, _super);
  28618. function LensFlaresOptimization() {
  28619. _super.apply(this, arguments);
  28620. this.apply = function (scene) {
  28621. scene.lensFlaresEnabled = false;
  28622. return true;
  28623. };
  28624. }
  28625. return LensFlaresOptimization;
  28626. })(SceneOptimization);
  28627. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28628. var ParticlesOptimization = (function (_super) {
  28629. __extends(ParticlesOptimization, _super);
  28630. function ParticlesOptimization() {
  28631. _super.apply(this, arguments);
  28632. this.apply = function (scene) {
  28633. scene.particlesEnabled = false;
  28634. return true;
  28635. };
  28636. }
  28637. return ParticlesOptimization;
  28638. })(SceneOptimization);
  28639. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28640. var RenderTargetsOptimization = (function (_super) {
  28641. __extends(RenderTargetsOptimization, _super);
  28642. function RenderTargetsOptimization() {
  28643. _super.apply(this, arguments);
  28644. this.apply = function (scene) {
  28645. scene.renderTargetsEnabled = false;
  28646. return true;
  28647. };
  28648. }
  28649. return RenderTargetsOptimization;
  28650. })(SceneOptimization);
  28651. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28652. var MergeMeshesOptimization = (function (_super) {
  28653. __extends(MergeMeshesOptimization, _super);
  28654. function MergeMeshesOptimization() {
  28655. var _this = this;
  28656. _super.apply(this, arguments);
  28657. this._canBeMerged = function (abstractMesh) {
  28658. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28659. return false;
  28660. }
  28661. var mesh = abstractMesh;
  28662. if (!mesh.isVisible || !mesh.isEnabled()) {
  28663. return false;
  28664. }
  28665. if (mesh.instances.length > 0) {
  28666. return false;
  28667. }
  28668. if (mesh.skeleton || mesh.hasLODLevels) {
  28669. return false;
  28670. }
  28671. return true;
  28672. };
  28673. this.apply = function (scene) {
  28674. var globalPool = scene.meshes.slice(0);
  28675. var globalLength = globalPool.length;
  28676. for (var index = 0; index < globalLength; index++) {
  28677. var currentPool = new Array();
  28678. var current = globalPool[index];
  28679. // Checks
  28680. if (!_this._canBeMerged(current)) {
  28681. continue;
  28682. }
  28683. currentPool.push(current);
  28684. // Find compatible meshes
  28685. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28686. var otherMesh = globalPool[subIndex];
  28687. if (!_this._canBeMerged(otherMesh)) {
  28688. continue;
  28689. }
  28690. if (otherMesh.material !== current.material) {
  28691. continue;
  28692. }
  28693. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28694. continue;
  28695. }
  28696. currentPool.push(otherMesh);
  28697. globalLength--;
  28698. globalPool.splice(subIndex, 1);
  28699. subIndex--;
  28700. }
  28701. if (currentPool.length < 2) {
  28702. continue;
  28703. }
  28704. // Merge meshes
  28705. BABYLON.Mesh.MergeMeshes(currentPool);
  28706. }
  28707. return true;
  28708. };
  28709. }
  28710. return MergeMeshesOptimization;
  28711. })(SceneOptimization);
  28712. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28713. // Options
  28714. var SceneOptimizerOptions = (function () {
  28715. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28716. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28717. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28718. this.targetFrameRate = targetFrameRate;
  28719. this.trackerDuration = trackerDuration;
  28720. this.optimizations = new Array();
  28721. }
  28722. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28723. var result = new SceneOptimizerOptions(targetFrameRate);
  28724. var priority = 0;
  28725. result.optimizations.push(new MergeMeshesOptimization(priority));
  28726. result.optimizations.push(new ShadowsOptimization(priority));
  28727. result.optimizations.push(new LensFlaresOptimization(priority));
  28728. // Next priority
  28729. priority++;
  28730. result.optimizations.push(new PostProcessesOptimization(priority));
  28731. result.optimizations.push(new ParticlesOptimization(priority));
  28732. // Next priority
  28733. priority++;
  28734. result.optimizations.push(new TextureOptimization(priority, 1024));
  28735. return result;
  28736. };
  28737. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28738. var result = new SceneOptimizerOptions(targetFrameRate);
  28739. var priority = 0;
  28740. result.optimizations.push(new MergeMeshesOptimization(priority));
  28741. result.optimizations.push(new ShadowsOptimization(priority));
  28742. result.optimizations.push(new LensFlaresOptimization(priority));
  28743. // Next priority
  28744. priority++;
  28745. result.optimizations.push(new PostProcessesOptimization(priority));
  28746. result.optimizations.push(new ParticlesOptimization(priority));
  28747. // Next priority
  28748. priority++;
  28749. result.optimizations.push(new TextureOptimization(priority, 512));
  28750. // Next priority
  28751. priority++;
  28752. result.optimizations.push(new RenderTargetsOptimization(priority));
  28753. // Next priority
  28754. priority++;
  28755. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28756. return result;
  28757. };
  28758. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28759. var result = new SceneOptimizerOptions(targetFrameRate);
  28760. var priority = 0;
  28761. result.optimizations.push(new MergeMeshesOptimization(priority));
  28762. result.optimizations.push(new ShadowsOptimization(priority));
  28763. result.optimizations.push(new LensFlaresOptimization(priority));
  28764. // Next priority
  28765. priority++;
  28766. result.optimizations.push(new PostProcessesOptimization(priority));
  28767. result.optimizations.push(new ParticlesOptimization(priority));
  28768. // Next priority
  28769. priority++;
  28770. result.optimizations.push(new TextureOptimization(priority, 256));
  28771. // Next priority
  28772. priority++;
  28773. result.optimizations.push(new RenderTargetsOptimization(priority));
  28774. // Next priority
  28775. priority++;
  28776. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28777. return result;
  28778. };
  28779. return SceneOptimizerOptions;
  28780. })();
  28781. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28782. // Scene optimizer tool
  28783. var SceneOptimizer = (function () {
  28784. function SceneOptimizer() {
  28785. }
  28786. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28787. // TODO: add an epsilon
  28788. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28789. if (onSuccess) {
  28790. onSuccess();
  28791. }
  28792. return;
  28793. }
  28794. // Apply current level of optimizations
  28795. var allDone = true;
  28796. var noOptimizationApplied = true;
  28797. for (var index = 0; index < options.optimizations.length; index++) {
  28798. var optimization = options.optimizations[index];
  28799. if (optimization.priority === currentPriorityLevel) {
  28800. noOptimizationApplied = false;
  28801. allDone = allDone && optimization.apply(scene);
  28802. }
  28803. }
  28804. // If no optimization was applied, this is a failure :(
  28805. if (noOptimizationApplied) {
  28806. if (onFailure) {
  28807. onFailure();
  28808. }
  28809. return;
  28810. }
  28811. // If all optimizations were done, move to next level
  28812. if (allDone) {
  28813. currentPriorityLevel++;
  28814. }
  28815. // Let's the system running for a specific amount of time before checking FPS
  28816. scene.executeWhenReady(function () {
  28817. setTimeout(function () {
  28818. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28819. }, options.trackerDuration);
  28820. });
  28821. };
  28822. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28823. if (!options) {
  28824. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28825. }
  28826. // Let's the system running for a specific amount of time before checking FPS
  28827. scene.executeWhenReady(function () {
  28828. setTimeout(function () {
  28829. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28830. }, options.trackerDuration);
  28831. });
  28832. };
  28833. return SceneOptimizer;
  28834. })();
  28835. BABYLON.SceneOptimizer = SceneOptimizer;
  28836. })(BABYLON || (BABYLON = {}));
  28837. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28838. var BABYLON;
  28839. (function (BABYLON) {
  28840. var Internals;
  28841. (function (Internals) {
  28842. var MeshLODLevel = (function () {
  28843. function MeshLODLevel(distance, mesh) {
  28844. this.distance = distance;
  28845. this.mesh = mesh;
  28846. }
  28847. return MeshLODLevel;
  28848. })();
  28849. Internals.MeshLODLevel = MeshLODLevel;
  28850. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28851. })(BABYLON || (BABYLON = {}));
  28852. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28853. var BABYLON;
  28854. (function (BABYLON) {
  28855. var AudioEngine = (function () {
  28856. function AudioEngine() {
  28857. this._audioContext = null;
  28858. this._audioContextInitialized = false;
  28859. this.canUseWebAudio = false;
  28860. this.WarnedWebAudioUnsupported = false;
  28861. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28862. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28863. this.canUseWebAudio = true;
  28864. }
  28865. }
  28866. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28867. get: function () {
  28868. if (!this._audioContextInitialized) {
  28869. this._initializeAudioContext();
  28870. }
  28871. return this._audioContext;
  28872. },
  28873. enumerable: true,
  28874. configurable: true
  28875. });
  28876. AudioEngine.prototype._initializeAudioContext = function () {
  28877. try {
  28878. if (this.canUseWebAudio) {
  28879. this._audioContext = new AudioContext();
  28880. // create a global volume gain node
  28881. this.masterGain = this._audioContext.createGain();
  28882. this.masterGain.gain.value = 1;
  28883. this.masterGain.connect(this._audioContext.destination);
  28884. this._audioContextInitialized = true;
  28885. }
  28886. }
  28887. catch (e) {
  28888. this.canUseWebAudio = false;
  28889. BABYLON.Tools.Error("Web Audio: " + e.message);
  28890. }
  28891. };
  28892. AudioEngine.prototype.dispose = function () {
  28893. if (this.canUseWebAudio && this._audioContextInitialized) {
  28894. if (this._connectedAnalyser) {
  28895. this._connectedAnalyser.stopDebugCanvas();
  28896. this._connectedAnalyser.dispose();
  28897. this.masterGain.disconnect();
  28898. this.masterGain.connect(this._audioContext.destination);
  28899. this._connectedAnalyser = null;
  28900. }
  28901. this.masterGain.gain.value = 1;
  28902. }
  28903. this.WarnedWebAudioUnsupported = false;
  28904. };
  28905. AudioEngine.prototype.getGlobalVolume = function () {
  28906. if (this.canUseWebAudio && this._audioContextInitialized) {
  28907. return this.masterGain.gain.value;
  28908. }
  28909. else {
  28910. return -1;
  28911. }
  28912. };
  28913. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28914. if (this.canUseWebAudio && this._audioContextInitialized) {
  28915. this.masterGain.gain.value = newVolume;
  28916. }
  28917. };
  28918. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28919. if (this._connectedAnalyser) {
  28920. this._connectedAnalyser.stopDebugCanvas();
  28921. }
  28922. if (this.canUseWebAudio && this._audioContextInitialized) {
  28923. this._connectedAnalyser = analyser;
  28924. this.masterGain.disconnect();
  28925. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28926. }
  28927. };
  28928. return AudioEngine;
  28929. })();
  28930. BABYLON.AudioEngine = AudioEngine;
  28931. })(BABYLON || (BABYLON = {}));
  28932. //# sourceMappingURL=babylon.audioEngine.js.map
  28933. var BABYLON;
  28934. (function (BABYLON) {
  28935. var Sound = (function () {
  28936. /**
  28937. * Create a sound and attach it to a scene
  28938. * @param name Name of your sound
  28939. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  28940. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  28941. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  28942. */
  28943. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  28944. var _this = this;
  28945. this.autoplay = false;
  28946. this.loop = false;
  28947. this.useCustomAttenuation = false;
  28948. this.spatialSound = false;
  28949. this.refDistance = 1;
  28950. this.rolloffFactor = 1;
  28951. this.maxDistance = 100;
  28952. this.distanceModel = "linear";
  28953. this._panningModel = "equalpower";
  28954. this._playbackRate = 1;
  28955. this._startTime = 0;
  28956. this._startOffset = 0;
  28957. this._position = BABYLON.Vector3.Zero();
  28958. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  28959. this._volume = 1;
  28960. this._isLoaded = false;
  28961. this._isReadyToPlay = false;
  28962. this.isPlaying = false;
  28963. this.isPaused = false;
  28964. this._isDirectional = false;
  28965. // Used if you'd like to create a directional sound.
  28966. // If not set, the sound will be omnidirectional
  28967. this._coneInnerAngle = 360;
  28968. this._coneOuterAngle = 360;
  28969. this._coneOuterGain = 0;
  28970. this.name = name;
  28971. this._scene = scene;
  28972. this._readyToPlayCallback = readyToPlayCallback;
  28973. // Default custom attenuation function is a linear attenuation
  28974. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  28975. if (currentDistance < maxDistance) {
  28976. return currentVolume * (1 - currentDistance / maxDistance);
  28977. }
  28978. else {
  28979. return 0;
  28980. }
  28981. };
  28982. if (options) {
  28983. this.autoplay = options.autoplay || false;
  28984. this.loop = options.loop || false;
  28985. // if volume === 0, we need another way to check this option
  28986. if (options.volume !== undefined) {
  28987. this._volume = options.volume;
  28988. }
  28989. this.spatialSound = options.spatialSound || false;
  28990. this.maxDistance = options.maxDistance || 100;
  28991. this.useCustomAttenuation = options.useCustomAttenuation || false;
  28992. this.rolloffFactor = options.rolloffFactor || 1;
  28993. this.refDistance = options.refDistance || 1;
  28994. this.distanceModel = options.distanceModel || "linear";
  28995. this._playbackRate = options.playbackRate || 1;
  28996. }
  28997. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28998. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  28999. this._soundGain.gain.value = this._volume;
  29000. this._inputAudioNode = this._soundGain;
  29001. this._ouputAudioNode = this._soundGain;
  29002. if (this.spatialSound) {
  29003. this._createSpatialParameters();
  29004. }
  29005. this._scene.mainSoundTrack.AddSound(this);
  29006. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  29007. if (urlOrArrayBuffer) {
  29008. // If it's an URL
  29009. if (typeof (urlOrArrayBuffer) === "string") {
  29010. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  29011. }
  29012. else {
  29013. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  29014. this._soundLoaded(urlOrArrayBuffer);
  29015. }
  29016. else {
  29017. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  29018. }
  29019. }
  29020. }
  29021. }
  29022. else {
  29023. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  29024. this._scene.mainSoundTrack.AddSound(this);
  29025. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  29026. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  29027. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  29028. }
  29029. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  29030. if (this._readyToPlayCallback) {
  29031. window.setTimeout(function () {
  29032. _this._readyToPlayCallback();
  29033. }, 1000);
  29034. }
  29035. }
  29036. }
  29037. Sound.prototype.dispose = function () {
  29038. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  29039. if (this.isPlaying) {
  29040. this.stop();
  29041. }
  29042. this._isReadyToPlay = false;
  29043. if (this.soundTrackId === -1) {
  29044. this._scene.mainSoundTrack.RemoveSound(this);
  29045. }
  29046. else {
  29047. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  29048. }
  29049. if (this._soundGain) {
  29050. this._soundGain.disconnect();
  29051. this._soundGain = null;
  29052. }
  29053. if (this._soundPanner) {
  29054. this._soundPanner.disconnect();
  29055. this._soundPanner = null;
  29056. }
  29057. if (this._soundSource) {
  29058. this._soundSource.disconnect();
  29059. this._soundSource = null;
  29060. }
  29061. this._audioBuffer = null;
  29062. if (this._connectedMesh) {
  29063. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  29064. this._connectedMesh = null;
  29065. }
  29066. }
  29067. };
  29068. Sound.prototype._soundLoaded = function (audioData) {
  29069. var _this = this;
  29070. this._isLoaded = true;
  29071. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  29072. _this._audioBuffer = buffer;
  29073. _this._isReadyToPlay = true;
  29074. if (_this.autoplay) {
  29075. _this.play();
  29076. }
  29077. if (_this._readyToPlayCallback) {
  29078. _this._readyToPlayCallback();
  29079. }
  29080. }, function (error) { BABYLON.Tools.Error("Error while decoding audio data: " + error.err); });
  29081. };
  29082. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  29083. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29084. this._audioBuffer = audioBuffer;
  29085. this._isReadyToPlay = true;
  29086. }
  29087. };
  29088. Sound.prototype.updateOptions = function (options) {
  29089. if (options) {
  29090. this.loop = options.loop || this.loop;
  29091. this.maxDistance = options.maxDistance || this.maxDistance;
  29092. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  29093. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  29094. this.refDistance = options.refDistance || this.refDistance;
  29095. this.distanceModel = options.distanceModel || this.distanceModel;
  29096. this._playbackRate = options.playbackRate || this._playbackRate;
  29097. }
  29098. };
  29099. Sound.prototype._createSpatialParameters = function () {
  29100. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29101. if (this._scene.headphone) {
  29102. this._panningModel = "HRTF";
  29103. }
  29104. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  29105. if (this.useCustomAttenuation) {
  29106. // Tricks to disable in a way embedded Web Audio attenuation
  29107. this._soundPanner.distanceModel = "linear";
  29108. this._soundPanner.maxDistance = Number.MAX_VALUE;
  29109. this._soundPanner.refDistance = 1;
  29110. this._soundPanner.rolloffFactor = 1;
  29111. this._soundPanner.panningModel = this._panningModel;
  29112. }
  29113. else {
  29114. this._soundPanner.distanceModel = this.distanceModel;
  29115. this._soundPanner.maxDistance = this.maxDistance;
  29116. this._soundPanner.refDistance = this.refDistance;
  29117. this._soundPanner.rolloffFactor = this.rolloffFactor;
  29118. this._soundPanner.panningModel = this._panningModel;
  29119. }
  29120. this._soundPanner.connect(this._ouputAudioNode);
  29121. this._inputAudioNode = this._soundPanner;
  29122. }
  29123. };
  29124. Sound.prototype.switchPanningModelToHRTF = function () {
  29125. this._panningModel = "HRTF";
  29126. this._switchPanningModel();
  29127. };
  29128. Sound.prototype.switchPanningModelToEqualPower = function () {
  29129. this._panningModel = "equalpower";
  29130. this._switchPanningModel();
  29131. };
  29132. Sound.prototype._switchPanningModel = function () {
  29133. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29134. this._soundPanner.panningModel = this._panningModel;
  29135. }
  29136. };
  29137. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  29138. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29139. this._ouputAudioNode.disconnect();
  29140. this._ouputAudioNode.connect(soundTrackAudioNode);
  29141. }
  29142. };
  29143. /**
  29144. * Transform this sound into a directional source
  29145. * @param coneInnerAngle Size of the inner cone in degree
  29146. * @param coneOuterAngle Size of the outer cone in degree
  29147. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  29148. */
  29149. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  29150. if (coneOuterAngle < coneInnerAngle) {
  29151. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  29152. return;
  29153. }
  29154. this._coneInnerAngle = coneInnerAngle;
  29155. this._coneOuterAngle = coneOuterAngle;
  29156. this._coneOuterGain = coneOuterGain;
  29157. this._isDirectional = true;
  29158. if (this.isPlaying && this.loop) {
  29159. this.stop();
  29160. this.play();
  29161. }
  29162. };
  29163. Sound.prototype.setPosition = function (newPosition) {
  29164. this._position = newPosition;
  29165. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29166. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29167. }
  29168. };
  29169. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  29170. this._localDirection = newLocalDirection;
  29171. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  29172. this._updateDirection();
  29173. }
  29174. };
  29175. Sound.prototype._updateDirection = function () {
  29176. var mat = this._connectedMesh.getWorldMatrix();
  29177. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  29178. direction.normalize();
  29179. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  29180. };
  29181. Sound.prototype.updateDistanceFromListener = function () {
  29182. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  29183. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  29184. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  29185. }
  29186. };
  29187. Sound.prototype.setAttenuationFunction = function (callback) {
  29188. this._customAttenuationFunction = callback;
  29189. };
  29190. /**
  29191. * Play the sound
  29192. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  29193. */
  29194. Sound.prototype.play = function (time) {
  29195. var _this = this;
  29196. if (this._isReadyToPlay && this._scene.audioEnabled) {
  29197. try {
  29198. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29199. if (!this._soundSource) {
  29200. if (this.spatialSound) {
  29201. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29202. if (this._isDirectional) {
  29203. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  29204. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  29205. this._soundPanner.coneOuterGain = this._coneOuterGain;
  29206. if (this._connectedMesh) {
  29207. this._updateDirection();
  29208. }
  29209. else {
  29210. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  29211. }
  29212. }
  29213. }
  29214. }
  29215. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  29216. this._soundSource.buffer = this._audioBuffer;
  29217. this._soundSource.connect(this._inputAudioNode);
  29218. this._soundSource.loop = this.loop;
  29219. this._soundSource.playbackRate.value = this._playbackRate;
  29220. this._startTime = startTime;
  29221. this._soundSource.onended = function () { _this._onended(); };
  29222. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  29223. this.isPlaying = true;
  29224. this.isPaused = false;
  29225. }
  29226. catch (ex) {
  29227. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  29228. }
  29229. }
  29230. };
  29231. Sound.prototype._onended = function () {
  29232. this.isPlaying = false;
  29233. if (this.onended) {
  29234. this.onended();
  29235. }
  29236. };
  29237. /**
  29238. * Stop the sound
  29239. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  29240. */
  29241. Sound.prototype.stop = function (time) {
  29242. if (this.isPlaying) {
  29243. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29244. this._soundSource.stop(stopTime);
  29245. this.isPlaying = false;
  29246. }
  29247. };
  29248. Sound.prototype.pause = function () {
  29249. if (this.isPlaying) {
  29250. this.stop(0);
  29251. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  29252. this.isPaused = true;
  29253. }
  29254. };
  29255. Sound.prototype.setVolume = function (newVolume, time) {
  29256. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  29257. if (time) {
  29258. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  29259. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  29260. }
  29261. else {
  29262. this._soundGain.gain.value = newVolume;
  29263. }
  29264. }
  29265. this._volume = newVolume;
  29266. };
  29267. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  29268. this._playbackRate = newPlaybackRate;
  29269. if (this.isPlaying) {
  29270. this._soundSource.playbackRate.value = this._playbackRate;
  29271. }
  29272. };
  29273. Sound.prototype.getVolume = function () {
  29274. return this._volume;
  29275. };
  29276. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  29277. var _this = this;
  29278. this._connectedMesh = meshToConnectTo;
  29279. if (!this.spatialSound) {
  29280. this._createSpatialParameters();
  29281. this.spatialSound = true;
  29282. if (this.isPlaying && this.loop) {
  29283. this.stop();
  29284. this.play();
  29285. }
  29286. }
  29287. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  29288. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  29289. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  29290. };
  29291. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  29292. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  29293. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  29294. this._updateDirection();
  29295. }
  29296. };
  29297. return Sound;
  29298. })();
  29299. BABYLON.Sound = Sound;
  29300. })(BABYLON || (BABYLON = {}));
  29301. //# sourceMappingURL=babylon.sound.js.map
  29302. var BABYLON;
  29303. (function (BABYLON) {
  29304. var SoundTrack = (function () {
  29305. function SoundTrack(scene, options) {
  29306. this.id = -1;
  29307. this._isMainTrack = false;
  29308. this._scene = scene;
  29309. this._audioEngine = BABYLON.Engine.audioEngine;
  29310. this.soundCollection = new Array();
  29311. if (this._audioEngine.canUseWebAudio) {
  29312. this._trackGain = this._audioEngine.audioContext.createGain();
  29313. this._trackGain.connect(this._audioEngine.masterGain);
  29314. if (options) {
  29315. if (options.volume) {
  29316. this._trackGain.gain.value = options.volume;
  29317. }
  29318. if (options.mainTrack) {
  29319. this._isMainTrack = options.mainTrack;
  29320. }
  29321. }
  29322. }
  29323. if (!this._isMainTrack) {
  29324. this._scene.soundTracks.push(this);
  29325. this.id = this._scene.soundTracks.length - 1;
  29326. }
  29327. }
  29328. SoundTrack.prototype.dispose = function () {
  29329. if (this._audioEngine.canUseWebAudio) {
  29330. if (this._connectedAnalyser) {
  29331. this._connectedAnalyser.stopDebugCanvas();
  29332. }
  29333. while (this.soundCollection.length) {
  29334. this.soundCollection[0].dispose();
  29335. }
  29336. this._trackGain.disconnect();
  29337. this._trackGain = null;
  29338. }
  29339. };
  29340. SoundTrack.prototype.AddSound = function (sound) {
  29341. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29342. sound.connectToSoundTrackAudioNode(this._trackGain);
  29343. }
  29344. if (sound.soundTrackId) {
  29345. if (sound.soundTrackId === -1) {
  29346. this._scene.mainSoundTrack.RemoveSound(sound);
  29347. }
  29348. else {
  29349. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  29350. }
  29351. }
  29352. this.soundCollection.push(sound);
  29353. sound.soundTrackId = this.id;
  29354. };
  29355. SoundTrack.prototype.RemoveSound = function (sound) {
  29356. var index = this.soundCollection.indexOf(sound);
  29357. if (index !== -1) {
  29358. this.soundCollection.splice(index, 1);
  29359. }
  29360. };
  29361. SoundTrack.prototype.setVolume = function (newVolume) {
  29362. if (this._audioEngine.canUseWebAudio) {
  29363. this._trackGain.gain.value = newVolume;
  29364. }
  29365. };
  29366. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  29367. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29368. for (var i = 0; i < this.soundCollection.length; i++) {
  29369. this.soundCollection[i].switchPanningModelToHRTF();
  29370. }
  29371. }
  29372. };
  29373. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  29374. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29375. for (var i = 0; i < this.soundCollection.length; i++) {
  29376. this.soundCollection[i].switchPanningModelToEqualPower();
  29377. }
  29378. }
  29379. };
  29380. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  29381. if (this._connectedAnalyser) {
  29382. this._connectedAnalyser.stopDebugCanvas();
  29383. }
  29384. this._connectedAnalyser = analyser;
  29385. if (this._audioEngine.canUseWebAudio) {
  29386. this._trackGain.disconnect();
  29387. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  29388. }
  29389. };
  29390. return SoundTrack;
  29391. })();
  29392. BABYLON.SoundTrack = SoundTrack;
  29393. })(BABYLON || (BABYLON = {}));
  29394. //# sourceMappingURL=babylon.soundtrack.js.map
  29395. var BABYLON;
  29396. (function (BABYLON) {
  29397. var DebugLayer = (function () {
  29398. function DebugLayer(scene) {
  29399. var _this = this;
  29400. this._transformationMatrix = BABYLON.Matrix.Identity();
  29401. this._enabled = false;
  29402. this._labelsEnabled = false;
  29403. this._displayStatistics = true;
  29404. this._displayTree = false;
  29405. this._displayLogs = false;
  29406. this._identityMatrix = BABYLON.Matrix.Identity();
  29407. this.axisRatio = 0.02;
  29408. this.accentColor = "orange";
  29409. this._scene = scene;
  29410. this._syncPositions = function () {
  29411. var engine = _this._scene.getEngine();
  29412. var canvasRect = engine.getRenderingCanvasClientRect();
  29413. if (_this._showUI) {
  29414. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29415. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29416. _this._statsDiv.style.width = "400px";
  29417. _this._statsDiv.style.height = "auto";
  29418. _this._statsSubsetDiv.style.maxHeight = "240px";
  29419. _this._optionsDiv.style.left = "0px";
  29420. _this._optionsDiv.style.top = "10px";
  29421. _this._optionsDiv.style.width = "200px";
  29422. _this._optionsDiv.style.height = "auto";
  29423. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29424. _this._logDiv.style.left = "0px";
  29425. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29426. _this._logDiv.style.width = "600px";
  29427. _this._logDiv.style.height = "160px";
  29428. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29429. _this._treeDiv.style.top = "10px";
  29430. _this._treeDiv.style.width = "300px";
  29431. _this._treeDiv.style.height = "auto";
  29432. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29433. }
  29434. _this._globalDiv.style.left = canvasRect.left + "px";
  29435. _this._globalDiv.style.top = canvasRect.top + "px";
  29436. _this._drawingCanvas.style.left = "0px";
  29437. _this._drawingCanvas.style.top = "0px";
  29438. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29439. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29440. var devicePixelRatio = window.devicePixelRatio || 1;
  29441. var context = _this._drawingContext;
  29442. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29443. context.mozBackingStorePixelRatio ||
  29444. context.msBackingStorePixelRatio ||
  29445. context.oBackingStorePixelRatio ||
  29446. context.backingStorePixelRatio || 1;
  29447. _this._ratio = devicePixelRatio / backingStoreRatio;
  29448. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29449. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29450. };
  29451. this._onCanvasClick = function (evt) {
  29452. _this._clickPosition = {
  29453. x: evt.clientX * _this._ratio,
  29454. y: evt.clientY * _this._ratio
  29455. };
  29456. };
  29457. this._syncUI = function () {
  29458. if (_this._showUI) {
  29459. if (_this._displayStatistics) {
  29460. _this._displayStats();
  29461. _this._statsDiv.style.display = "";
  29462. }
  29463. else {
  29464. _this._statsDiv.style.display = "none";
  29465. }
  29466. if (_this._displayLogs) {
  29467. _this._logDiv.style.display = "";
  29468. }
  29469. else {
  29470. _this._logDiv.style.display = "none";
  29471. }
  29472. if (_this._displayTree) {
  29473. _this._treeDiv.style.display = "";
  29474. if (_this._needToRefreshMeshesTree) {
  29475. _this._needToRefreshMeshesTree = false;
  29476. _this._refreshMeshesTreeContent();
  29477. }
  29478. }
  29479. else {
  29480. _this._treeDiv.style.display = "none";
  29481. }
  29482. }
  29483. };
  29484. this._syncData = function () {
  29485. if (_this._labelsEnabled || !_this._showUI) {
  29486. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29487. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29488. var engine = _this._scene.getEngine();
  29489. var viewport = _this._camera.viewport;
  29490. var globalViewport = viewport.toGlobal(engine);
  29491. // Meshes
  29492. var meshes = _this._camera.getActiveMeshes();
  29493. for (var index = 0; index < meshes.length; index++) {
  29494. var mesh = meshes.data[index];
  29495. var position = mesh.getBoundingInfo().boundingSphere.center;
  29496. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29497. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29498. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29499. }
  29500. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29501. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29502. }
  29503. }
  29504. // Cameras
  29505. var cameras = _this._scene.cameras;
  29506. for (index = 0; index < cameras.length; index++) {
  29507. var camera = cameras[index];
  29508. if (camera === _this._camera) {
  29509. continue;
  29510. }
  29511. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29512. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29513. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29514. _this._camera.detachControl(engine.getRenderingCanvas());
  29515. _this._camera = camera;
  29516. _this._camera.attachControl(engine.getRenderingCanvas());
  29517. }, function () { return "purple"; });
  29518. }
  29519. }
  29520. // Lights
  29521. var lights = _this._scene.lights;
  29522. for (index = 0; index < lights.length; index++) {
  29523. var light = lights[index];
  29524. if (light.position) {
  29525. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29526. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29527. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29528. light.setEnabled(!light.isEnabled());
  29529. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29530. }
  29531. }
  29532. }
  29533. }
  29534. _this._clickPosition = undefined;
  29535. };
  29536. }
  29537. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29538. while (this._treeSubsetDiv.hasChildNodes()) {
  29539. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29540. }
  29541. // Add meshes
  29542. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29543. sortedArray.sort(function (a, b) {
  29544. if (a.name === b.name) {
  29545. return 0;
  29546. }
  29547. return (a.name > b.name) ? 1 : -1;
  29548. });
  29549. for (var index = 0; index < sortedArray.length; index++) {
  29550. var mesh = sortedArray[index];
  29551. if (!mesh.isEnabled()) {
  29552. continue;
  29553. }
  29554. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29555. m.isVisible = element.checked;
  29556. }, mesh);
  29557. }
  29558. };
  29559. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29560. this._drawingContext.beginPath();
  29561. this._drawingContext.moveTo(zero.x, zero.y);
  29562. this._drawingContext.lineTo(unit.x, unit.y);
  29563. this._drawingContext.strokeStyle = color;
  29564. this._drawingContext.lineWidth = 4;
  29565. this._drawingContext.stroke();
  29566. this._drawingContext.font = "normal 14px Segoe UI";
  29567. this._drawingContext.fillStyle = color;
  29568. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29569. };
  29570. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29571. var position = mesh.getBoundingInfo().boundingSphere.center;
  29572. var worldMatrix = mesh.getWorldMatrix();
  29573. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29574. var unit = (unprojectedVector.subtract(position)).length();
  29575. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29576. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29577. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29578. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29579. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29580. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29581. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29582. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29583. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29584. };
  29585. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29586. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29587. this._drawingContext.font = "normal 12px Segoe UI";
  29588. var textMetrics = this._drawingContext.measureText(text);
  29589. var centerX = projectedPosition.x - textMetrics.width / 2;
  29590. var centerY = projectedPosition.y;
  29591. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29592. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29593. onClick();
  29594. }
  29595. this._drawingContext.beginPath();
  29596. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29597. this._drawingContext.fillStyle = getFillStyle();
  29598. this._drawingContext.globalAlpha = 0.5;
  29599. this._drawingContext.fill();
  29600. this._drawingContext.globalAlpha = 1.0;
  29601. this._drawingContext.strokeStyle = '#FFFFFF';
  29602. this._drawingContext.lineWidth = 1;
  29603. this._drawingContext.stroke();
  29604. this._drawingContext.fillStyle = "#FFFFFF";
  29605. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29606. this._drawingContext.beginPath();
  29607. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29608. this._drawingContext.fill();
  29609. }
  29610. };
  29611. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29612. if (!this._clickPosition) {
  29613. return false;
  29614. }
  29615. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29616. return false;
  29617. }
  29618. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29619. return false;
  29620. }
  29621. return true;
  29622. };
  29623. DebugLayer.prototype.isVisible = function () {
  29624. return this._enabled;
  29625. };
  29626. DebugLayer.prototype.hide = function () {
  29627. if (!this._enabled) {
  29628. return;
  29629. }
  29630. this._enabled = false;
  29631. var engine = this._scene.getEngine();
  29632. this._scene.unregisterBeforeRender(this._syncData);
  29633. this._scene.unregisterAfterRender(this._syncUI);
  29634. document.body.removeChild(this._globalDiv);
  29635. window.removeEventListener("resize", this._syncPositions);
  29636. this._scene.forceShowBoundingBoxes = false;
  29637. this._scene.forceWireframe = false;
  29638. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29639. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29640. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29641. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29642. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29643. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29644. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29645. this._scene.shadowsEnabled = true;
  29646. this._scene.particlesEnabled = true;
  29647. this._scene.postProcessesEnabled = true;
  29648. this._scene.collisionsEnabled = true;
  29649. this._scene.lightsEnabled = true;
  29650. this._scene.texturesEnabled = true;
  29651. this._scene.lensFlaresEnabled = true;
  29652. this._scene.proceduralTexturesEnabled = true;
  29653. this._scene.renderTargetsEnabled = true;
  29654. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29655. };
  29656. DebugLayer.prototype.show = function (showUI, camera) {
  29657. if (showUI === void 0) { showUI = true; }
  29658. if (camera === void 0) { camera = null; }
  29659. if (this._enabled) {
  29660. return;
  29661. }
  29662. this._enabled = true;
  29663. if (camera) {
  29664. this._camera = camera;
  29665. }
  29666. else {
  29667. this._camera = this._scene.activeCamera;
  29668. }
  29669. this._showUI = showUI;
  29670. var engine = this._scene.getEngine();
  29671. this._globalDiv = document.createElement("div");
  29672. document.body.appendChild(this._globalDiv);
  29673. this._generateDOMelements();
  29674. window.addEventListener("resize", this._syncPositions);
  29675. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29676. this._syncPositions();
  29677. this._scene.registerBeforeRender(this._syncData);
  29678. this._scene.registerAfterRender(this._syncUI);
  29679. };
  29680. DebugLayer.prototype._clearLabels = function () {
  29681. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29682. for (var index = 0; index < this._scene.meshes.length; index++) {
  29683. var mesh = this._scene.meshes[index];
  29684. mesh.renderOverlay = false;
  29685. }
  29686. };
  29687. DebugLayer.prototype._generateheader = function (root, text) {
  29688. var header = document.createElement("div");
  29689. header.innerHTML = text + "&nbsp;";
  29690. header.style.textAlign = "right";
  29691. header.style.width = "100%";
  29692. header.style.color = "white";
  29693. header.style.backgroundColor = "Black";
  29694. header.style.padding = "5px 5px 4px 0px";
  29695. header.style.marginLeft = "-5px";
  29696. header.style.fontWeight = "bold";
  29697. root.appendChild(header);
  29698. };
  29699. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29700. var label = document.createElement("label");
  29701. label.innerHTML = title;
  29702. label.style.color = color;
  29703. root.appendChild(label);
  29704. root.appendChild(document.createElement("br"));
  29705. };
  29706. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29707. if (tag === void 0) { tag = null; }
  29708. var label = document.createElement("label");
  29709. var boundingBoxesCheckbox = document.createElement("input");
  29710. boundingBoxesCheckbox.type = "checkbox";
  29711. boundingBoxesCheckbox.checked = initialState;
  29712. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29713. task(evt.target, tag);
  29714. });
  29715. label.appendChild(boundingBoxesCheckbox);
  29716. var container = document.createElement("span");
  29717. var leftPart = document.createElement("span");
  29718. var rightPart = document.createElement("span");
  29719. rightPart.style.cssFloat = "right";
  29720. leftPart.innerHTML = leftTitle;
  29721. rightPart.innerHTML = rightTitle;
  29722. rightPart.style.fontSize = "12px";
  29723. rightPart.style.maxWidth = "200px";
  29724. container.appendChild(leftPart);
  29725. container.appendChild(rightPart);
  29726. label.appendChild(container);
  29727. root.appendChild(label);
  29728. root.appendChild(document.createElement("br"));
  29729. };
  29730. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29731. if (tag === void 0) { tag = null; }
  29732. var label = document.createElement("label");
  29733. var checkBox = document.createElement("input");
  29734. checkBox.type = "checkbox";
  29735. checkBox.checked = initialState;
  29736. checkBox.addEventListener("change", function (evt) {
  29737. task(evt.target, tag);
  29738. });
  29739. label.appendChild(checkBox);
  29740. label.appendChild(document.createTextNode(title));
  29741. root.appendChild(label);
  29742. root.appendChild(document.createElement("br"));
  29743. };
  29744. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29745. if (tag === void 0) { tag = null; }
  29746. var button = document.createElement("button");
  29747. button.innerHTML = title;
  29748. button.style.height = "24px";
  29749. button.style.color = "#444444";
  29750. button.style.border = "1px solid white";
  29751. button.className = "debugLayerButton";
  29752. button.addEventListener("click", function (evt) {
  29753. task(evt.target, tag);
  29754. });
  29755. root.appendChild(button);
  29756. root.appendChild(document.createElement("br"));
  29757. };
  29758. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29759. if (tag === void 0) { tag = null; }
  29760. var label = document.createElement("label");
  29761. var boundingBoxesRadio = document.createElement("input");
  29762. boundingBoxesRadio.type = "radio";
  29763. boundingBoxesRadio.name = name;
  29764. boundingBoxesRadio.checked = initialState;
  29765. boundingBoxesRadio.addEventListener("change", function (evt) {
  29766. task(evt.target, tag);
  29767. });
  29768. label.appendChild(boundingBoxesRadio);
  29769. label.appendChild(document.createTextNode(title));
  29770. root.appendChild(label);
  29771. root.appendChild(document.createElement("br"));
  29772. };
  29773. DebugLayer.prototype._generateDOMelements = function () {
  29774. var _this = this;
  29775. this._globalDiv.id = "DebugLayer";
  29776. this._globalDiv.style.position = "absolute";
  29777. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29778. this._globalDiv.style.fontSize = "14px";
  29779. this._globalDiv.style.color = "white";
  29780. // Drawing canvas
  29781. this._drawingCanvas = document.createElement("canvas");
  29782. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29783. this._drawingCanvas.style.position = "absolute";
  29784. this._drawingCanvas.style.pointerEvents = "none";
  29785. this._drawingContext = this._drawingCanvas.getContext("2d");
  29786. this._globalDiv.appendChild(this._drawingCanvas);
  29787. if (this._showUI) {
  29788. var background = "rgba(128, 128, 128, 0.4)";
  29789. var border = "rgb(180, 180, 180) solid 1px";
  29790. // Stats
  29791. this._statsDiv = document.createElement("div");
  29792. this._statsDiv.id = "DebugLayerStats";
  29793. this._statsDiv.style.border = border;
  29794. this._statsDiv.style.position = "absolute";
  29795. this._statsDiv.style.background = background;
  29796. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29797. this._generateheader(this._statsDiv, "STATISTICS");
  29798. this._statsSubsetDiv = document.createElement("div");
  29799. this._statsSubsetDiv.style.paddingTop = "5px";
  29800. this._statsSubsetDiv.style.paddingBottom = "5px";
  29801. this._statsSubsetDiv.style.overflowY = "auto";
  29802. this._statsDiv.appendChild(this._statsSubsetDiv);
  29803. // Tree
  29804. this._treeDiv = document.createElement("div");
  29805. this._treeDiv.id = "DebugLayerTree";
  29806. this._treeDiv.style.border = border;
  29807. this._treeDiv.style.position = "absolute";
  29808. this._treeDiv.style.background = background;
  29809. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29810. this._treeDiv.style.display = "none";
  29811. this._generateheader(this._treeDiv, "MESHES TREE");
  29812. this._treeSubsetDiv = document.createElement("div");
  29813. this._treeSubsetDiv.style.paddingTop = "5px";
  29814. this._treeSubsetDiv.style.paddingRight = "5px";
  29815. this._treeSubsetDiv.style.overflowY = "auto";
  29816. this._treeSubsetDiv.style.maxHeight = "300px";
  29817. this._treeDiv.appendChild(this._treeSubsetDiv);
  29818. this._needToRefreshMeshesTree = true;
  29819. // Logs
  29820. this._logDiv = document.createElement("div");
  29821. this._logDiv.style.border = border;
  29822. this._logDiv.id = "DebugLayerLogs";
  29823. this._logDiv.style.position = "absolute";
  29824. this._logDiv.style.background = background;
  29825. this._logDiv.style.padding = "0px 0px 0px 5px";
  29826. this._logDiv.style.display = "none";
  29827. this._generateheader(this._logDiv, "LOGS");
  29828. this._logSubsetDiv = document.createElement("div");
  29829. this._logSubsetDiv.style.height = "127px";
  29830. this._logSubsetDiv.style.paddingTop = "5px";
  29831. this._logSubsetDiv.style.overflowY = "auto";
  29832. this._logSubsetDiv.style.fontSize = "12px";
  29833. this._logSubsetDiv.style.fontFamily = "consolas";
  29834. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29835. this._logDiv.appendChild(this._logSubsetDiv);
  29836. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29837. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29838. };
  29839. // Options
  29840. this._optionsDiv = document.createElement("div");
  29841. this._optionsDiv.id = "DebugLayerOptions";
  29842. this._optionsDiv.style.border = border;
  29843. this._optionsDiv.style.position = "absolute";
  29844. this._optionsDiv.style.background = background;
  29845. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29846. this._optionsDiv.style.overflowY = "auto";
  29847. this._generateheader(this._optionsDiv, "OPTIONS");
  29848. this._optionsSubsetDiv = document.createElement("div");
  29849. this._optionsSubsetDiv.style.paddingTop = "5px";
  29850. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29851. this._optionsSubsetDiv.style.overflowY = "auto";
  29852. this._optionsSubsetDiv.style.maxHeight = "200px";
  29853. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29854. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29855. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29856. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29857. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29858. _this._displayTree = element.checked;
  29859. _this._needToRefreshMeshesTree = true;
  29860. });
  29861. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29862. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29863. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29864. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29865. _this._labelsEnabled = element.checked;
  29866. if (!_this._labelsEnabled) {
  29867. _this._clearLabels();
  29868. }
  29869. });
  29870. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29871. if (element.checked) {
  29872. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29873. }
  29874. else {
  29875. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29876. }
  29877. });
  29878. ;
  29879. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29880. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29881. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29882. if (element.checked) {
  29883. _this._scene.forceWireframe = false;
  29884. _this._scene.forcePointsCloud = false;
  29885. }
  29886. });
  29887. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29888. if (element.checked) {
  29889. _this._scene.forceWireframe = true;
  29890. _this._scene.forcePointsCloud = false;
  29891. }
  29892. });
  29893. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29894. if (element.checked) {
  29895. _this._scene.forceWireframe = false;
  29896. _this._scene.forcePointsCloud = true;
  29897. }
  29898. });
  29899. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29900. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29901. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29902. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29903. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29904. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29905. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29906. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29907. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29908. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29909. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29910. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29911. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29912. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29913. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29914. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29915. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29916. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29917. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29918. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29919. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29920. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29921. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29922. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29923. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29924. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29925. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29926. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29927. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29928. if (element.checked) {
  29929. _this._scene.headphone = true;
  29930. }
  29931. });
  29932. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29933. if (element.checked) {
  29934. _this._scene.headphone = false;
  29935. }
  29936. });
  29937. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29938. _this._scene.audioEnabled = !element.checked;
  29939. });
  29940. }
  29941. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29942. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29943. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29944. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29945. this._globalDiv.appendChild(this._statsDiv);
  29946. this._globalDiv.appendChild(this._logDiv);
  29947. this._globalDiv.appendChild(this._optionsDiv);
  29948. this._globalDiv.appendChild(this._treeDiv);
  29949. }
  29950. };
  29951. DebugLayer.prototype._displayStats = function () {
  29952. var scene = this._scene;
  29953. var engine = scene.getEngine();
  29954. var glInfo = engine.getGlInfo();
  29955. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29956. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29957. + "<b>Count</b><br>"
  29958. + "Total meshes: " + scene.meshes.length + "<br>"
  29959. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29960. + "Total materials: " + scene.materials.length + "<br>"
  29961. + "Total textures: " + scene.textures.length + "<br>"
  29962. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29963. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29964. + "Active bones: " + scene.getActiveBones() + "<br>"
  29965. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29966. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  29967. + "<b>Duration</b><br>"
  29968. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29969. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29970. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29971. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29972. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29973. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29974. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  29975. + "</div>"
  29976. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29977. + "<b>Extensions</b><br>"
  29978. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29979. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29980. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29981. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  29982. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29983. + "<b>Caps.</b><br>"
  29984. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29985. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29986. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  29987. + "</div><br>"
  29988. + "<b>Info</b><br>"
  29989. + glInfo.version + "<br>"
  29990. + glInfo.renderer + "<br>";
  29991. if (this.customStatsFunction) {
  29992. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29993. }
  29994. };
  29995. return DebugLayer;
  29996. })();
  29997. BABYLON.DebugLayer = DebugLayer;
  29998. })(BABYLON || (BABYLON = {}));
  29999. //# sourceMappingURL=babylon.debugLayer.js.map
  30000. var __extends = this.__extends || function (d, b) {
  30001. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30002. function __() { this.constructor = d; }
  30003. __.prototype = b.prototype;
  30004. d.prototype = new __();
  30005. };
  30006. var BABYLON;
  30007. (function (BABYLON) {
  30008. var RawTexture = (function (_super) {
  30009. __extends(RawTexture, _super);
  30010. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  30011. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30012. if (invertY === void 0) { invertY = false; }
  30013. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30014. _super.call(this, null, scene, !generateMipMaps, invertY);
  30015. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  30016. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30017. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30018. }
  30019. // Statics
  30020. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30021. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30022. if (invertY === void 0) { invertY = false; }
  30023. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30024. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  30025. };
  30026. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30027. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30028. if (invertY === void 0) { invertY = false; }
  30029. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30030. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  30031. };
  30032. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30033. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30034. if (invertY === void 0) { invertY = false; }
  30035. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30036. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  30037. };
  30038. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30039. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30040. if (invertY === void 0) { invertY = false; }
  30041. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30042. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  30043. };
  30044. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30045. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30046. if (invertY === void 0) { invertY = false; }
  30047. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30048. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  30049. };
  30050. return RawTexture;
  30051. })(BABYLON.Texture);
  30052. BABYLON.RawTexture = RawTexture;
  30053. })(BABYLON || (BABYLON = {}));
  30054. //# sourceMappingURL=babylon.rawTexture.js.map
  30055. var __extends = this.__extends || function (d, b) {
  30056. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30057. function __() { this.constructor = d; }
  30058. __.prototype = b.prototype;
  30059. d.prototype = new __();
  30060. };
  30061. var BABYLON;
  30062. (function (BABYLON) {
  30063. var IndexedVector2 = (function (_super) {
  30064. __extends(IndexedVector2, _super);
  30065. function IndexedVector2(original, index) {
  30066. _super.call(this, original.x, original.y);
  30067. this.index = index;
  30068. }
  30069. return IndexedVector2;
  30070. })(BABYLON.Vector2);
  30071. var PolygonPoints = (function () {
  30072. function PolygonPoints() {
  30073. this.elements = new Array();
  30074. }
  30075. PolygonPoints.prototype.add = function (originalPoints) {
  30076. var _this = this;
  30077. var result = new Array();
  30078. originalPoints.forEach(function (point) {
  30079. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  30080. var newPoint = new IndexedVector2(point, _this.elements.length);
  30081. result.push(newPoint);
  30082. _this.elements.push(newPoint);
  30083. }
  30084. });
  30085. return result;
  30086. };
  30087. PolygonPoints.prototype.computeBounds = function () {
  30088. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  30089. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  30090. this.elements.forEach(function (point) {
  30091. // x
  30092. if (point.x < lmin.x) {
  30093. lmin.x = point.x;
  30094. }
  30095. else if (point.x > lmax.x) {
  30096. lmax.x = point.x;
  30097. }
  30098. // y
  30099. if (point.y < lmin.y) {
  30100. lmin.y = point.y;
  30101. }
  30102. else if (point.y > lmax.y) {
  30103. lmax.y = point.y;
  30104. }
  30105. });
  30106. return {
  30107. min: lmin,
  30108. max: lmax,
  30109. width: lmax.x - lmin.x,
  30110. height: lmax.y - lmin.y
  30111. };
  30112. };
  30113. return PolygonPoints;
  30114. })();
  30115. var Polygon = (function () {
  30116. function Polygon() {
  30117. }
  30118. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  30119. return [
  30120. new BABYLON.Vector2(xmin, ymin),
  30121. new BABYLON.Vector2(xmax, ymin),
  30122. new BABYLON.Vector2(xmax, ymax),
  30123. new BABYLON.Vector2(xmin, ymax)
  30124. ];
  30125. };
  30126. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  30127. if (cx === void 0) { cx = 0; }
  30128. if (cy === void 0) { cy = 0; }
  30129. if (numberOfSides === void 0) { numberOfSides = 32; }
  30130. var result = new Array();
  30131. var angle = 0;
  30132. var increment = (Math.PI * 2) / numberOfSides;
  30133. for (var i = 0; i < numberOfSides; i++) {
  30134. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  30135. angle -= increment;
  30136. }
  30137. return result;
  30138. };
  30139. Polygon.Parse = function (input) {
  30140. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  30141. var i, result = [];
  30142. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  30143. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  30144. }
  30145. return result;
  30146. };
  30147. Polygon.StartingAt = function (x, y) {
  30148. return BABYLON.Path2.StartingAt(x, y);
  30149. };
  30150. return Polygon;
  30151. })();
  30152. BABYLON.Polygon = Polygon;
  30153. var PolygonMeshBuilder = (function () {
  30154. function PolygonMeshBuilder(name, contours, scene) {
  30155. this._points = new PolygonPoints();
  30156. this._outlinepoints = new PolygonPoints();
  30157. this._holes = [];
  30158. if (!("poly2tri" in window)) {
  30159. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  30160. }
  30161. this._name = name;
  30162. this._scene = scene;
  30163. var points;
  30164. if (contours instanceof BABYLON.Path2) {
  30165. points = contours.getPoints();
  30166. }
  30167. else {
  30168. points = contours;
  30169. }
  30170. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  30171. this._outlinepoints.add(points);
  30172. }
  30173. PolygonMeshBuilder.prototype.addHole = function (hole) {
  30174. this._swctx.addHole(this._points.add(hole));
  30175. var holepoints = new PolygonPoints();
  30176. holepoints.add(hole);
  30177. this._holes.push(holepoints);
  30178. return this;
  30179. };
  30180. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  30181. var _this = this;
  30182. if (updatable === void 0) { updatable = false; }
  30183. var result = new BABYLON.Mesh(this._name, this._scene);
  30184. var normals = [];
  30185. var positions = [];
  30186. var uvs = [];
  30187. var bounds = this._points.computeBounds();
  30188. this._points.elements.forEach(function (p) {
  30189. normals.push(0, 1.0, 0);
  30190. positions.push(p.x, 0, p.y);
  30191. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  30192. });
  30193. var indices = [];
  30194. this._swctx.triangulate();
  30195. this._swctx.getTriangles().forEach(function (triangle) {
  30196. triangle.getPoints().forEach(function (point) {
  30197. indices.push(point.index);
  30198. });
  30199. });
  30200. if (depth > 0) {
  30201. var positionscount = (positions.length / 3); //get the current pointcount
  30202. this._points.elements.forEach(function (p) {
  30203. normals.push(0, -1.0, 0);
  30204. positions.push(p.x, -depth, p.y);
  30205. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  30206. });
  30207. var p1; //we need to change order of point so the triangles are made in the rigth way.
  30208. var p2;
  30209. var poscounter = 0;
  30210. this._swctx.getTriangles().forEach(function (triangle) {
  30211. triangle.getPoints().forEach(function (point) {
  30212. switch (poscounter) {
  30213. case 0:
  30214. p1 = point;
  30215. break;
  30216. case 1:
  30217. p2 = point;
  30218. break;
  30219. case 2:
  30220. indices.push(point.index + positionscount);
  30221. indices.push(p2.index + positionscount);
  30222. indices.push(p1.index + positionscount);
  30223. poscounter = -1;
  30224. break;
  30225. }
  30226. poscounter++;
  30227. //indices.push((<IndexedVector2>point).index + positionscount);
  30228. });
  30229. });
  30230. //Add the sides
  30231. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  30232. this._holes.forEach(function (hole) {
  30233. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  30234. });
  30235. }
  30236. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  30237. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  30238. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  30239. result.setIndices(indices);
  30240. return result;
  30241. };
  30242. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  30243. var StartIndex = positions.length / 3;
  30244. var ulength = 0;
  30245. for (var i = 0; i < points.elements.length; i++) {
  30246. var p = points.elements[i];
  30247. var p1;
  30248. if ((i + 1) > points.elements.length - 1) {
  30249. p1 = points.elements[0];
  30250. }
  30251. else {
  30252. p1 = points.elements[i + 1];
  30253. }
  30254. positions.push(p.x, 0, p.y);
  30255. positions.push(p.x, -depth, p.y);
  30256. positions.push(p1.x, 0, p1.y);
  30257. positions.push(p1.x, -depth, p1.y);
  30258. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  30259. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  30260. var v3 = v2.subtract(v1);
  30261. var v4 = new BABYLON.Vector3(0, 1, 0);
  30262. var vn = BABYLON.Vector3.Cross(v3, v4);
  30263. vn = vn.normalize();
  30264. uvs.push(ulength / bounds.width, 0);
  30265. uvs.push(ulength / bounds.width, 1);
  30266. ulength += v3.length();
  30267. uvs.push((ulength / bounds.width), 0);
  30268. uvs.push((ulength / bounds.width), 1);
  30269. if (!flip) {
  30270. normals.push(-vn.x, -vn.y, -vn.z);
  30271. normals.push(-vn.x, -vn.y, -vn.z);
  30272. normals.push(-vn.x, -vn.y, -vn.z);
  30273. normals.push(-vn.x, -vn.y, -vn.z);
  30274. indices.push(StartIndex);
  30275. indices.push(StartIndex + 1);
  30276. indices.push(StartIndex + 2);
  30277. indices.push(StartIndex + 1);
  30278. indices.push(StartIndex + 3);
  30279. indices.push(StartIndex + 2);
  30280. }
  30281. else {
  30282. normals.push(vn.x, vn.y, vn.z);
  30283. normals.push(vn.x, vn.y, vn.z);
  30284. normals.push(vn.x, vn.y, vn.z);
  30285. normals.push(vn.x, vn.y, vn.z);
  30286. indices.push(StartIndex);
  30287. indices.push(StartIndex + 2);
  30288. indices.push(StartIndex + 1);
  30289. indices.push(StartIndex + 1);
  30290. indices.push(StartIndex + 2);
  30291. indices.push(StartIndex + 3);
  30292. }
  30293. StartIndex += 4;
  30294. }
  30295. ;
  30296. };
  30297. return PolygonMeshBuilder;
  30298. })();
  30299. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  30300. })(BABYLON || (BABYLON = {}));
  30301. //# sourceMappingURL=babylon.polygonMesh.js.map
  30302. var BABYLON;
  30303. (function (BABYLON) {
  30304. var SimplificationSettings = (function () {
  30305. function SimplificationSettings(quality, distance, optimizeMesh) {
  30306. this.quality = quality;
  30307. this.distance = distance;
  30308. this.optimizeMesh = optimizeMesh;
  30309. }
  30310. return SimplificationSettings;
  30311. })();
  30312. BABYLON.SimplificationSettings = SimplificationSettings;
  30313. var SimplificationQueue = (function () {
  30314. function SimplificationQueue() {
  30315. this.running = false;
  30316. this._simplificationArray = [];
  30317. }
  30318. SimplificationQueue.prototype.addTask = function (task) {
  30319. this._simplificationArray.push(task);
  30320. };
  30321. SimplificationQueue.prototype.executeNext = function () {
  30322. var task = this._simplificationArray.pop();
  30323. if (task) {
  30324. this.running = true;
  30325. this.runSimplification(task);
  30326. }
  30327. else {
  30328. this.running = false;
  30329. }
  30330. };
  30331. SimplificationQueue.prototype.runSimplification = function (task) {
  30332. var _this = this;
  30333. if (task.parallelProcessing) {
  30334. //parallel simplifier
  30335. task.settings.forEach(function (setting) {
  30336. var simplifier = _this.getSimplifier(task);
  30337. simplifier.simplify(setting, function (newMesh) {
  30338. task.mesh.addLODLevel(setting.distance, newMesh);
  30339. newMesh.isVisible = true;
  30340. //check if it is the last
  30341. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30342. //all done, run the success callback.
  30343. task.successCallback();
  30344. }
  30345. _this.executeNext();
  30346. });
  30347. });
  30348. }
  30349. else {
  30350. //single simplifier.
  30351. var simplifier = this.getSimplifier(task);
  30352. var runDecimation = function (setting, callback) {
  30353. simplifier.simplify(setting, function (newMesh) {
  30354. task.mesh.addLODLevel(setting.distance, newMesh);
  30355. newMesh.isVisible = true;
  30356. //run the next quality level
  30357. callback();
  30358. });
  30359. };
  30360. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30361. runDecimation(task.settings[loop.index], function () {
  30362. loop.executeNext();
  30363. });
  30364. }, function () {
  30365. //execution ended, run the success callback.
  30366. if (task.successCallback) {
  30367. task.successCallback();
  30368. }
  30369. _this.executeNext();
  30370. });
  30371. }
  30372. };
  30373. SimplificationQueue.prototype.getSimplifier = function (task) {
  30374. switch (task.simplificationType) {
  30375. case SimplificationType.QUADRATIC:
  30376. default:
  30377. return new QuadraticErrorSimplification(task.mesh);
  30378. }
  30379. };
  30380. return SimplificationQueue;
  30381. })();
  30382. BABYLON.SimplificationQueue = SimplificationQueue;
  30383. /**
  30384. * The implemented types of simplification.
  30385. * At the moment only Quadratic Error Decimation is implemented.
  30386. */
  30387. (function (SimplificationType) {
  30388. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30389. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30390. var SimplificationType = BABYLON.SimplificationType;
  30391. var DecimationTriangle = (function () {
  30392. function DecimationTriangle(vertices) {
  30393. this.vertices = vertices;
  30394. this.error = new Array(4);
  30395. this.deleted = false;
  30396. this.isDirty = false;
  30397. this.deletePending = false;
  30398. this.borderFactor = 0;
  30399. }
  30400. return DecimationTriangle;
  30401. })();
  30402. BABYLON.DecimationTriangle = DecimationTriangle;
  30403. var DecimationVertex = (function () {
  30404. function DecimationVertex(position, id) {
  30405. this.position = position;
  30406. this.id = id;
  30407. this.isBorder = true;
  30408. this.q = new QuadraticMatrix();
  30409. this.triangleCount = 0;
  30410. this.triangleStart = 0;
  30411. this.originalOffsets = [];
  30412. }
  30413. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30414. this.position.copyFrom(newPosition);
  30415. };
  30416. return DecimationVertex;
  30417. })();
  30418. BABYLON.DecimationVertex = DecimationVertex;
  30419. var QuadraticMatrix = (function () {
  30420. function QuadraticMatrix(data) {
  30421. this.data = new Array(10);
  30422. for (var i = 0; i < 10; ++i) {
  30423. if (data && data[i]) {
  30424. this.data[i] = data[i];
  30425. }
  30426. else {
  30427. this.data[i] = 0;
  30428. }
  30429. }
  30430. }
  30431. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30432. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30433. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30434. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30435. return det;
  30436. };
  30437. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30438. for (var i = 0; i < 10; ++i) {
  30439. this.data[i] += matrix.data[i];
  30440. }
  30441. };
  30442. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30443. for (var i = 0; i < 10; ++i) {
  30444. this.data[i] += data[i];
  30445. }
  30446. };
  30447. QuadraticMatrix.prototype.add = function (matrix) {
  30448. var m = new QuadraticMatrix();
  30449. for (var i = 0; i < 10; ++i) {
  30450. m.data[i] = this.data[i] + matrix.data[i];
  30451. }
  30452. return m;
  30453. };
  30454. QuadraticMatrix.FromData = function (a, b, c, d) {
  30455. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30456. };
  30457. //returning an array to avoid garbage collection
  30458. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30459. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30460. };
  30461. return QuadraticMatrix;
  30462. })();
  30463. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30464. var Reference = (function () {
  30465. function Reference(vertexId, triangleId) {
  30466. this.vertexId = vertexId;
  30467. this.triangleId = triangleId;
  30468. }
  30469. return Reference;
  30470. })();
  30471. BABYLON.Reference = Reference;
  30472. /**
  30473. * An implementation of the Quadratic Error simplification algorithm.
  30474. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30475. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30476. * @author RaananW
  30477. */
  30478. var QuadraticErrorSimplification = (function () {
  30479. function QuadraticErrorSimplification(_mesh) {
  30480. this._mesh = _mesh;
  30481. this.initialized = false;
  30482. this.syncIterations = 5000;
  30483. this.aggressiveness = 7;
  30484. this.decimationIterations = 100;
  30485. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30486. }
  30487. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30488. var _this = this;
  30489. this.initDecimatedMesh();
  30490. //iterating through the submeshes array, one after the other.
  30491. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30492. _this.initWithMesh(loop.index, function () {
  30493. _this.runDecimation(settings, loop.index, function () {
  30494. loop.executeNext();
  30495. });
  30496. }, settings.optimizeMesh);
  30497. }, function () {
  30498. setTimeout(function () {
  30499. successCallback(_this._reconstructedMesh);
  30500. }, 0);
  30501. });
  30502. };
  30503. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30504. var _this = this;
  30505. var gCount = 0;
  30506. triangle.vertices.forEach(function (vertex) {
  30507. var count = 0;
  30508. var vPos = vertex.position;
  30509. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30510. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30511. ++count;
  30512. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  30513. ++count;
  30514. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  30515. ++count;
  30516. if (count > 1) {
  30517. ++gCount;
  30518. }
  30519. ;
  30520. });
  30521. if (gCount > 1) {
  30522. console.log(triangle, gCount);
  30523. }
  30524. return gCount > 1;
  30525. };
  30526. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30527. var _this = this;
  30528. var targetCount = ~~(this.triangles.length * settings.quality);
  30529. var deletedTriangles = 0;
  30530. var triangleCount = this.triangles.length;
  30531. var iterationFunction = function (iteration, callback) {
  30532. setTimeout(function () {
  30533. if (iteration % 5 === 0) {
  30534. _this.updateMesh(iteration === 0);
  30535. }
  30536. for (var i = 0; i < _this.triangles.length; ++i) {
  30537. _this.triangles[i].isDirty = false;
  30538. }
  30539. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30540. var trianglesIterator = function (i) {
  30541. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30542. var t = _this.triangles[tIdx];
  30543. if (!t)
  30544. return;
  30545. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30546. return;
  30547. }
  30548. for (var j = 0; j < 3; ++j) {
  30549. if (t.error[j] < threshold) {
  30550. var deleted0 = [];
  30551. var deleted1 = [];
  30552. var v0 = t.vertices[j];
  30553. var v1 = t.vertices[(j + 1) % 3];
  30554. if (v0.isBorder !== v1.isBorder)
  30555. continue;
  30556. var p = BABYLON.Vector3.Zero();
  30557. var n = BABYLON.Vector3.Zero();
  30558. var uv = BABYLON.Vector2.Zero();
  30559. var color = new BABYLON.Color4(0, 0, 0, 1);
  30560. _this.calculateError(v0, v1, p, n, uv, color);
  30561. var delTr = [];
  30562. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30563. continue;
  30564. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30565. continue;
  30566. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30567. continue;
  30568. var uniqueArray = [];
  30569. delTr.forEach(function (deletedT) {
  30570. if (uniqueArray.indexOf(deletedT) === -1) {
  30571. deletedT.deletePending = true;
  30572. uniqueArray.push(deletedT);
  30573. }
  30574. });
  30575. if (uniqueArray.length % 2 != 0) {
  30576. continue;
  30577. }
  30578. v0.q = v1.q.add(v0.q);
  30579. v0.updatePosition(p);
  30580. var tStart = _this.references.length;
  30581. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30582. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30583. var tCount = _this.references.length - tStart;
  30584. if (tCount <= v0.triangleCount) {
  30585. if (tCount) {
  30586. for (var c = 0; c < tCount; c++) {
  30587. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30588. }
  30589. }
  30590. }
  30591. else {
  30592. v0.triangleStart = tStart;
  30593. }
  30594. v0.triangleCount = tCount;
  30595. break;
  30596. }
  30597. }
  30598. };
  30599. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30600. }, 0);
  30601. };
  30602. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30603. if (triangleCount - deletedTriangles <= targetCount)
  30604. loop.breakLoop();
  30605. else {
  30606. iterationFunction(loop.index, function () {
  30607. loop.executeNext();
  30608. });
  30609. }
  30610. }, function () {
  30611. setTimeout(function () {
  30612. //reconstruct this part of the mesh
  30613. _this.reconstructMesh(submeshIndex);
  30614. successCallback();
  30615. }, 0);
  30616. });
  30617. };
  30618. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30619. var _this = this;
  30620. this.vertices = [];
  30621. this.triangles = [];
  30622. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30623. var indices = this._mesh.getIndices();
  30624. var submesh = this._mesh.subMeshes[submeshIndex];
  30625. var findInVertices = function (positionToSearch) {
  30626. if (optimizeMesh) {
  30627. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30628. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30629. return _this.vertices[ii];
  30630. }
  30631. }
  30632. }
  30633. return null;
  30634. };
  30635. var vertexReferences = [];
  30636. var vertexInit = function (i) {
  30637. var offset = i + submesh.verticesStart;
  30638. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30639. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30640. vertex.originalOffsets.push(offset);
  30641. if (vertex.id == _this.vertices.length) {
  30642. _this.vertices.push(vertex);
  30643. }
  30644. vertexReferences.push(vertex.id);
  30645. };
  30646. //var totalVertices = mesh.getTotalVertices();
  30647. var totalVertices = submesh.verticesCount;
  30648. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30649. var indicesInit = function (i) {
  30650. var offset = (submesh.indexStart / 3) + i;
  30651. var pos = (offset * 3);
  30652. var i0 = indices[pos + 0];
  30653. var i1 = indices[pos + 1];
  30654. var i2 = indices[pos + 2];
  30655. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30656. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30657. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30658. var triangle = new DecimationTriangle([v0, v1, v2]);
  30659. triangle.originalOffset = pos;
  30660. _this.triangles.push(triangle);
  30661. };
  30662. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30663. _this.init(callback);
  30664. });
  30665. });
  30666. };
  30667. QuadraticErrorSimplification.prototype.init = function (callback) {
  30668. var _this = this;
  30669. var triangleInit1 = function (i) {
  30670. var t = _this.triangles[i];
  30671. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30672. for (var j = 0; j < 3; j++) {
  30673. 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))));
  30674. }
  30675. };
  30676. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30677. var triangleInit2 = function (i) {
  30678. var t = _this.triangles[i];
  30679. for (var j = 0; j < 3; ++j) {
  30680. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30681. }
  30682. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30683. };
  30684. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30685. _this.initialized = true;
  30686. callback();
  30687. });
  30688. });
  30689. };
  30690. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30691. var newTriangles = [];
  30692. var i;
  30693. for (i = 0; i < this.vertices.length; ++i) {
  30694. this.vertices[i].triangleCount = 0;
  30695. }
  30696. var t;
  30697. var j;
  30698. for (i = 0; i < this.triangles.length; ++i) {
  30699. if (!this.triangles[i].deleted) {
  30700. t = this.triangles[i];
  30701. for (j = 0; j < 3; ++j) {
  30702. t.vertices[j].triangleCount = 1;
  30703. }
  30704. newTriangles.push(t);
  30705. }
  30706. }
  30707. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30708. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30709. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30710. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30711. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30712. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30713. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30714. var vertexCount = 0;
  30715. for (i = 0; i < this.vertices.length; ++i) {
  30716. var vertex = this.vertices[i];
  30717. vertex.id = vertexCount;
  30718. if (vertex.triangleCount) {
  30719. vertex.originalOffsets.forEach(function (originalOffset) {
  30720. newPositionData.push(vertex.position.x);
  30721. newPositionData.push(vertex.position.y);
  30722. newPositionData.push(vertex.position.z);
  30723. newNormalData.push(normalData[originalOffset * 3]);
  30724. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30725. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30726. if (uvs && uvs.length) {
  30727. newUVsData.push(uvs[(originalOffset * 2)]);
  30728. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30729. }
  30730. else if (colorsData && colorsData.length) {
  30731. newColorsData.push(colorsData[(originalOffset * 4)]);
  30732. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30733. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30734. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30735. }
  30736. ++vertexCount;
  30737. });
  30738. }
  30739. }
  30740. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30741. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30742. var submeshesArray = this._reconstructedMesh.subMeshes;
  30743. this._reconstructedMesh.subMeshes = [];
  30744. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30745. var originalIndices = this._mesh.getIndices();
  30746. for (i = 0; i < newTriangles.length; ++i) {
  30747. var t = newTriangles[i];
  30748. //now get the new referencing point for each vertex
  30749. [0, 1, 2].forEach(function (idx) {
  30750. var id = originalIndices[t.originalOffset + idx];
  30751. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30752. if (offset < 0)
  30753. offset = 0;
  30754. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30755. });
  30756. }
  30757. //overwriting the old vertex buffers and indices.
  30758. this._reconstructedMesh.setIndices(newIndicesArray);
  30759. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30760. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30761. if (newUVsData.length > 0)
  30762. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30763. if (newColorsData.length > 0)
  30764. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30765. //create submesh
  30766. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30767. if (submeshIndex > 0) {
  30768. this._reconstructedMesh.subMeshes = [];
  30769. submeshesArray.forEach(function (submesh) {
  30770. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30771. });
  30772. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30773. }
  30774. };
  30775. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30776. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30777. this._reconstructedMesh.material = this._mesh.material;
  30778. this._reconstructedMesh.parent = this._mesh.parent;
  30779. this._reconstructedMesh.isVisible = false;
  30780. };
  30781. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30782. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30783. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30784. if (t.deleted)
  30785. continue;
  30786. var s = this.references[vertex1.triangleStart + i].vertexId;
  30787. var v1 = t.vertices[(s + 1) % 3];
  30788. var v2 = t.vertices[(s + 2) % 3];
  30789. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30790. deletedArray[i] = true;
  30791. delTr.push(t);
  30792. continue;
  30793. }
  30794. var d1 = v1.position.subtract(point);
  30795. d1 = d1.normalize();
  30796. var d2 = v2.position.subtract(point);
  30797. d2 = d2.normalize();
  30798. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30799. return true;
  30800. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30801. deletedArray[i] = false;
  30802. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30803. return true;
  30804. }
  30805. return false;
  30806. };
  30807. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30808. var newDeleted = deletedTriangles;
  30809. for (var i = 0; i < vertex.triangleCount; ++i) {
  30810. var ref = this.references[vertex.triangleStart + i];
  30811. var t = this.triangles[ref.triangleId];
  30812. if (t.deleted)
  30813. continue;
  30814. if (deletedArray[i] && t.deletePending) {
  30815. t.deleted = true;
  30816. newDeleted++;
  30817. continue;
  30818. }
  30819. t.vertices[ref.vertexId] = origVertex;
  30820. t.isDirty = true;
  30821. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30822. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30823. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30824. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30825. this.references.push(ref);
  30826. }
  30827. return newDeleted;
  30828. };
  30829. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30830. for (var i = 0; i < this.vertices.length; ++i) {
  30831. var vCount = [];
  30832. var vId = [];
  30833. var v = this.vertices[i];
  30834. var j;
  30835. for (j = 0; j < v.triangleCount; ++j) {
  30836. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30837. for (var ii = 0; ii < 3; ii++) {
  30838. var ofs = 0;
  30839. var vv = triangle.vertices[ii];
  30840. while (ofs < vCount.length) {
  30841. if (vId[ofs] === vv.id)
  30842. break;
  30843. ++ofs;
  30844. }
  30845. if (ofs === vCount.length) {
  30846. vCount.push(1);
  30847. vId.push(vv.id);
  30848. }
  30849. else {
  30850. vCount[ofs]++;
  30851. }
  30852. }
  30853. }
  30854. for (j = 0; j < vCount.length; ++j) {
  30855. if (vCount[j] === 1) {
  30856. this.vertices[vId[j]].isBorder = true;
  30857. }
  30858. else {
  30859. this.vertices[vId[j]].isBorder = false;
  30860. }
  30861. }
  30862. }
  30863. };
  30864. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30865. if (identifyBorders === void 0) { identifyBorders = false; }
  30866. var i;
  30867. if (!identifyBorders) {
  30868. var newTrianglesVector = [];
  30869. for (i = 0; i < this.triangles.length; ++i) {
  30870. if (!this.triangles[i].deleted) {
  30871. newTrianglesVector.push(this.triangles[i]);
  30872. }
  30873. }
  30874. this.triangles = newTrianglesVector;
  30875. }
  30876. for (i = 0; i < this.vertices.length; ++i) {
  30877. this.vertices[i].triangleCount = 0;
  30878. this.vertices[i].triangleStart = 0;
  30879. }
  30880. var t;
  30881. var j;
  30882. var v;
  30883. for (i = 0; i < this.triangles.length; ++i) {
  30884. t = this.triangles[i];
  30885. for (j = 0; j < 3; ++j) {
  30886. v = t.vertices[j];
  30887. v.triangleCount++;
  30888. }
  30889. }
  30890. var tStart = 0;
  30891. for (i = 0; i < this.vertices.length; ++i) {
  30892. this.vertices[i].triangleStart = tStart;
  30893. tStart += this.vertices[i].triangleCount;
  30894. this.vertices[i].triangleCount = 0;
  30895. }
  30896. var newReferences = new Array(this.triangles.length * 3);
  30897. for (i = 0; i < this.triangles.length; ++i) {
  30898. t = this.triangles[i];
  30899. for (j = 0; j < 3; ++j) {
  30900. v = t.vertices[j];
  30901. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30902. v.triangleCount++;
  30903. }
  30904. }
  30905. this.references = newReferences;
  30906. if (identifyBorders) {
  30907. this.identifyBorder();
  30908. }
  30909. };
  30910. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30911. var x = point.x;
  30912. var y = point.y;
  30913. var z = point.z;
  30914. 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
  30915. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30916. };
  30917. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30918. var q = vertex1.q.add(vertex2.q);
  30919. var border = vertex1.isBorder && vertex2.isBorder;
  30920. var error = 0;
  30921. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30922. if (qDet !== 0 && !border) {
  30923. if (!pointResult) {
  30924. pointResult = BABYLON.Vector3.Zero();
  30925. }
  30926. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30927. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30928. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30929. error = this.vertexError(q, pointResult);
  30930. }
  30931. else {
  30932. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30933. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30934. var error1 = this.vertexError(q, vertex1.position);
  30935. var error2 = this.vertexError(q, vertex2.position);
  30936. var error3 = this.vertexError(q, p3);
  30937. error = Math.min(error1, error2, error3);
  30938. if (error === error1) {
  30939. if (pointResult) {
  30940. pointResult.copyFrom(vertex1.position);
  30941. }
  30942. }
  30943. else if (error === error2) {
  30944. if (pointResult) {
  30945. pointResult.copyFrom(vertex2.position);
  30946. }
  30947. }
  30948. else {
  30949. if (pointResult) {
  30950. pointResult.copyFrom(p3);
  30951. }
  30952. }
  30953. }
  30954. return error;
  30955. };
  30956. return QuadraticErrorSimplification;
  30957. })();
  30958. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30959. })(BABYLON || (BABYLON = {}));
  30960. //# sourceMappingURL=babylon.meshSimplification.js.map
  30961. var BABYLON;
  30962. (function (BABYLON) {
  30963. var Analyser = (function () {
  30964. function Analyser(scene) {
  30965. this.SMOOTHING = 0.75;
  30966. this.FFT_SIZE = 512;
  30967. this.BARGRAPHAMPLITUDE = 256;
  30968. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  30969. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  30970. this._scene = scene;
  30971. this._audioEngine = BABYLON.Engine.audioEngine;
  30972. if (this._audioEngine.canUseWebAudio) {
  30973. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  30974. this._webAudioAnalyser.minDecibels = -140;
  30975. this._webAudioAnalyser.maxDecibels = 0;
  30976. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30977. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30978. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  30979. }
  30980. }
  30981. Analyser.prototype.getFrequencyBinCount = function () {
  30982. if (this._audioEngine.canUseWebAudio) {
  30983. return this._webAudioAnalyser.frequencyBinCount;
  30984. }
  30985. else {
  30986. return 0;
  30987. }
  30988. };
  30989. Analyser.prototype.getByteFrequencyData = function () {
  30990. if (this._audioEngine.canUseWebAudio) {
  30991. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30992. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30993. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  30994. }
  30995. return this._byteFreqs;
  30996. };
  30997. Analyser.prototype.getByteTimeDomainData = function () {
  30998. if (this._audioEngine.canUseWebAudio) {
  30999. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31000. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31001. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  31002. }
  31003. return this._byteTime;
  31004. };
  31005. Analyser.prototype.getFloatFrequencyData = function () {
  31006. if (this._audioEngine.canUseWebAudio) {
  31007. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31008. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31009. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  31010. }
  31011. return this._floatFreqs;
  31012. };
  31013. Analyser.prototype.drawDebugCanvas = function () {
  31014. var _this = this;
  31015. if (this._audioEngine.canUseWebAudio) {
  31016. if (!this._debugCanvas) {
  31017. this._debugCanvas = document.createElement("canvas");
  31018. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  31019. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  31020. this._debugCanvas.style.position = "absolute";
  31021. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  31022. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  31023. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  31024. document.body.appendChild(this._debugCanvas);
  31025. this._registerFunc = function () {
  31026. _this.drawDebugCanvas();
  31027. };
  31028. this._scene.registerBeforeRender(this._registerFunc);
  31029. }
  31030. if (this._registerFunc) {
  31031. var workingArray = this.getByteFrequencyData();
  31032. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  31033. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  31034. // Draw the frequency domain chart.
  31035. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  31036. var value = workingArray[i];
  31037. var percent = value / this.BARGRAPHAMPLITUDE;
  31038. var height = this.DEBUGCANVASSIZE.height * percent;
  31039. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  31040. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  31041. var hue = i / this.getFrequencyBinCount() * 360;
  31042. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  31043. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  31044. }
  31045. }
  31046. }
  31047. };
  31048. Analyser.prototype.stopDebugCanvas = function () {
  31049. if (this._debugCanvas) {
  31050. this._scene.unregisterBeforeRender(this._registerFunc);
  31051. this._registerFunc = null;
  31052. document.body.removeChild(this._debugCanvas);
  31053. this._debugCanvas = null;
  31054. this._debugCanvasContext = null;
  31055. }
  31056. };
  31057. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  31058. if (this._audioEngine.canUseWebAudio) {
  31059. inputAudioNode.connect(this._webAudioAnalyser);
  31060. this._webAudioAnalyser.connect(outputAudioNode);
  31061. }
  31062. };
  31063. Analyser.prototype.dispose = function () {
  31064. if (this._audioEngine.canUseWebAudio) {
  31065. this._webAudioAnalyser.disconnect();
  31066. }
  31067. };
  31068. return Analyser;
  31069. })();
  31070. BABYLON.Analyser = Analyser;
  31071. })(BABYLON || (BABYLON = {}));
  31072. //# sourceMappingURL=babylon.analyser.js.map
  31073. var BABYLON;
  31074. (function (BABYLON) {
  31075. var DepthRenderer = (function () {
  31076. function DepthRenderer(scene, type) {
  31077. var _this = this;
  31078. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  31079. this._viewMatrix = BABYLON.Matrix.Zero();
  31080. this._projectionMatrix = BABYLON.Matrix.Zero();
  31081. this._transformMatrix = BABYLON.Matrix.Zero();
  31082. this._worldViewProjection = BABYLON.Matrix.Zero();
  31083. this._scene = scene;
  31084. var engine = scene.getEngine();
  31085. // Render target
  31086. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  31087. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31088. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31089. this._depthMap.refreshRate = 1;
  31090. this._depthMap.renderParticles = false;
  31091. this._depthMap.renderList = null;
  31092. // set default depth value to 1.0 (far away)
  31093. this._depthMap.onClear = function (engine) {
  31094. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  31095. };
  31096. // Custom render function
  31097. var renderSubMesh = function (subMesh) {
  31098. var mesh = subMesh.getRenderingMesh();
  31099. var scene = _this._scene;
  31100. var engine = scene.getEngine();
  31101. // Culling
  31102. engine.setState(subMesh.getMaterial().backFaceCulling);
  31103. // Managing instances
  31104. var batch = mesh._getInstancesRenderList(subMesh._id);
  31105. if (batch.mustReturn) {
  31106. return;
  31107. }
  31108. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31109. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31110. engine.enableEffect(_this._effect);
  31111. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  31112. var material = subMesh.getMaterial();
  31113. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31114. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  31115. // Alpha test
  31116. if (material && material.needAlphaTesting()) {
  31117. var alphaTexture = material.getAlphaTestTexture();
  31118. _this._effect.setTexture("diffuseSampler", alphaTexture);
  31119. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31120. }
  31121. // Bones
  31122. if (mesh.useBones) {
  31123. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31124. }
  31125. // Draw
  31126. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  31127. }
  31128. };
  31129. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  31130. var index;
  31131. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31132. renderSubMesh(opaqueSubMeshes.data[index]);
  31133. }
  31134. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31135. renderSubMesh(alphaTestSubMeshes.data[index]);
  31136. }
  31137. };
  31138. }
  31139. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  31140. var defines = [];
  31141. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31142. var mesh = subMesh.getMesh();
  31143. var scene = mesh.getScene();
  31144. var material = subMesh.getMaterial();
  31145. // Alpha test
  31146. if (material && material.needAlphaTesting()) {
  31147. defines.push("#define ALPHATEST");
  31148. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31149. attribs.push(BABYLON.VertexBuffer.UVKind);
  31150. defines.push("#define UV1");
  31151. }
  31152. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31153. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31154. defines.push("#define UV2");
  31155. }
  31156. }
  31157. // Bones
  31158. if (mesh.useBones) {
  31159. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31160. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31161. defines.push("#define BONES");
  31162. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31163. }
  31164. // Instances
  31165. if (useInstances) {
  31166. defines.push("#define INSTANCES");
  31167. attribs.push("world0");
  31168. attribs.push("world1");
  31169. attribs.push("world2");
  31170. attribs.push("world3");
  31171. }
  31172. // Get correct effect
  31173. var join = defines.join("\n");
  31174. if (this._cachedDefines !== join) {
  31175. this._cachedDefines = join;
  31176. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  31177. }
  31178. return this._effect.isReady();
  31179. };
  31180. DepthRenderer.prototype.getDepthMap = function () {
  31181. return this._depthMap;
  31182. };
  31183. // Methods
  31184. DepthRenderer.prototype.dispose = function () {
  31185. this._depthMap.dispose();
  31186. };
  31187. return DepthRenderer;
  31188. })();
  31189. BABYLON.DepthRenderer = DepthRenderer;
  31190. })(BABYLON || (BABYLON = {}));
  31191. //# sourceMappingURL=babylon.depthRenderer.js.map
  31192. var __extends = this.__extends || function (d, b) {
  31193. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31194. function __() { this.constructor = d; }
  31195. __.prototype = b.prototype;
  31196. d.prototype = new __();
  31197. };
  31198. var BABYLON;
  31199. (function (BABYLON) {
  31200. var SSAORenderingPipeline = (function (_super) {
  31201. __extends(SSAORenderingPipeline, _super);
  31202. /**
  31203. * @constructor
  31204. * @param {string} name - The rendering pipeline name
  31205. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31206. * @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 }
  31207. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31208. */
  31209. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  31210. var _this = this;
  31211. _super.call(this, scene.getEngine(), name);
  31212. // Members
  31213. /**
  31214. * The PassPostProcess id in the pipeline that contains the original scene color
  31215. * @type {string}
  31216. */
  31217. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  31218. /**
  31219. * The SSAO PostProcess id in the pipeline
  31220. * @type {string}
  31221. */
  31222. this.SSAORenderEffect = "SSAORenderEffect";
  31223. /**
  31224. * The horizontal blur PostProcess id in the pipeline
  31225. * @type {string}
  31226. */
  31227. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  31228. /**
  31229. * The vertical blur PostProcess id in the pipeline
  31230. * @type {string}
  31231. */
  31232. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  31233. /**
  31234. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  31235. * @type {string}
  31236. */
  31237. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  31238. /**
  31239. * The output strength of the SSAO post-process. Default value is 1.0.
  31240. * @type {number}
  31241. */
  31242. this.totalStrength = 1.0;
  31243. /**
  31244. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  31245. * @type {number}
  31246. */
  31247. this.radius = 0.0002;
  31248. /**
  31249. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  31250. * Must not be equal to fallOff and superior to fallOff.
  31251. * Default value is 0.0075
  31252. * @type {number}
  31253. */
  31254. this.area = 0.0075;
  31255. /**
  31256. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  31257. * Must not be equal to area and inferior to area.
  31258. * Default value is 0.0002
  31259. * @type {number}
  31260. */
  31261. this.fallOff = 0.0002;
  31262. this._firstUpdate = true;
  31263. this._scene = scene;
  31264. // Set up assets
  31265. this._createRandomTexture();
  31266. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31267. var ssaoRatio = ratio.ssaoRatio || ratio;
  31268. var combineRatio = ratio.combineRatio || ratio;
  31269. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31270. this._createSSAOPostProcess(ssaoRatio);
  31271. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31272. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31273. this._createSSAOCombinePostProcess(combineRatio);
  31274. // Set up pipeline
  31275. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  31276. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  31277. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  31278. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  31279. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  31280. // Finish
  31281. scene.postProcessRenderPipelineManager.addPipeline(this);
  31282. if (cameras)
  31283. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31284. }
  31285. // Public Methods
  31286. /**
  31287. * Returns the horizontal blur PostProcess
  31288. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  31289. */
  31290. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  31291. return this._blurHPostProcess;
  31292. };
  31293. /**
  31294. * Returns the vertical blur PostProcess
  31295. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  31296. */
  31297. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  31298. return this._blurVPostProcess;
  31299. };
  31300. /**
  31301. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  31302. */
  31303. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31304. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31305. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31306. this._originalColorPostProcess = undefined;
  31307. this._ssaoPostProcess = undefined;
  31308. this._blurHPostProcess = undefined;
  31309. this._blurVPostProcess = undefined;
  31310. this._ssaoCombinePostProcess = undefined;
  31311. this._randomTexture.dispose();
  31312. if (disableDepthRender)
  31313. this._scene.disableDepthRenderer();
  31314. };
  31315. // Private Methods
  31316. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  31317. var _this = this;
  31318. var sampleSphere = [
  31319. 0.5381, 0.1856, -0.4319,
  31320. 0.1379, 0.2486, 0.4430,
  31321. 0.3371, 0.5679, -0.0057,
  31322. -0.6999, -0.0451, -0.0019,
  31323. 0.0689, -0.1598, -0.8547,
  31324. 0.0560, 0.0069, -0.1843,
  31325. -0.0146, 0.1402, 0.0762,
  31326. 0.0100, -0.1924, -0.0344,
  31327. -0.3577, -0.5301, -0.4358,
  31328. -0.3169, 0.1063, 0.0158,
  31329. 0.0103, -0.5869, 0.0046,
  31330. -0.0897, -0.4940, 0.3287,
  31331. 0.7119, -0.0154, -0.0918,
  31332. -0.0533, 0.0596, -0.5411,
  31333. 0.0352, -0.0631, 0.5460,
  31334. -0.4776, 0.2847, -0.0271
  31335. ];
  31336. var samplesFactor = 1.0 / 16.0;
  31337. 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);
  31338. this._ssaoPostProcess.onApply = function (effect) {
  31339. if (_this._firstUpdate) {
  31340. effect.setArray3("sampleSphere", sampleSphere);
  31341. effect.setFloat("samplesFactor", samplesFactor);
  31342. effect.setFloat("randTextureTiles", 4.0 / ratio);
  31343. _this._firstUpdate = false;
  31344. }
  31345. effect.setFloat("totalStrength", _this.totalStrength);
  31346. effect.setFloat("radius", _this.radius);
  31347. effect.setFloat("area", _this.area);
  31348. effect.setFloat("fallOff", _this.fallOff);
  31349. effect.setTexture("textureSampler", _this._depthTexture);
  31350. effect.setTexture("randomSampler", _this._randomTexture);
  31351. };
  31352. };
  31353. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  31354. var _this = this;
  31355. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31356. this._ssaoCombinePostProcess.onApply = function (effect) {
  31357. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  31358. };
  31359. };
  31360. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  31361. var size = 512;
  31362. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31363. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31364. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31365. var context = this._randomTexture.getContext();
  31366. var rand = function (min, max) {
  31367. return Math.random() * (max - min) + min;
  31368. };
  31369. for (var x = 0; x < size; x++) {
  31370. for (var y = 0; y < size; y++) {
  31371. var randVector = BABYLON.Vector3.Zero();
  31372. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  31373. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  31374. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  31375. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  31376. context.fillRect(x, y, 1, 1);
  31377. }
  31378. }
  31379. this._randomTexture.update(false);
  31380. };
  31381. return SSAORenderingPipeline;
  31382. })(BABYLON.PostProcessRenderPipeline);
  31383. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  31384. })(BABYLON || (BABYLON = {}));
  31385. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  31386. var __extends = this.__extends || function (d, b) {
  31387. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31388. function __() { this.constructor = d; }
  31389. __.prototype = b.prototype;
  31390. d.prototype = new __();
  31391. };
  31392. var BABYLON;
  31393. (function (BABYLON) {
  31394. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  31395. var VolumetricLightScatteringPostProcess = (function (_super) {
  31396. __extends(VolumetricLightScatteringPostProcess, _super);
  31397. /**
  31398. * @constructor
  31399. * @param {string} name - The post-process name
  31400. * @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)
  31401. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  31402. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  31403. * @param {number} samples - The post-process quality, default 100
  31404. * @param {number} samplingMode - The post-process filtering mode
  31405. * @param {BABYLON.Engine} engine - The babylon engine
  31406. * @param {boolean} reusable - If the post-process is reusable
  31407. */
  31408. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  31409. var _this = this;
  31410. if (samples === void 0) { samples = 100; }
  31411. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31412. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  31413. this._screenCoordinates = BABYLON.Vector2.Zero();
  31414. /**
  31415. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  31416. * @type {boolean}
  31417. */
  31418. this.useCustomMeshPosition = false;
  31419. /**
  31420. * If the post-process should inverse the light scattering direction
  31421. * @type {boolean}
  31422. */
  31423. this.invert = true;
  31424. /**
  31425. * Array containing the excluded meshes not rendered in the internal pass
  31426. */
  31427. this.excludedMeshes = new Array();
  31428. this.exposure = 0.3;
  31429. this.decay = 0.96815;
  31430. this.weight = 0.58767;
  31431. this.density = 0.926;
  31432. var scene = camera.getScene();
  31433. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  31434. // Configure mesh
  31435. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  31436. // Configure
  31437. this._createPass(scene, ratio.passRatio || ratio);
  31438. this.onApply = function (effect) {
  31439. _this._updateMeshScreenCoordinates(scene);
  31440. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  31441. effect.setFloat("exposure", _this.exposure);
  31442. effect.setFloat("decay", _this.decay);
  31443. effect.setFloat("weight", _this.weight);
  31444. effect.setFloat("density", _this.density);
  31445. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  31446. };
  31447. }
  31448. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  31449. var mesh = subMesh.getMesh();
  31450. var defines = [];
  31451. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31452. var material = subMesh.getMaterial();
  31453. var needUV = false;
  31454. // Render this.mesh as default
  31455. if (mesh === this.mesh) {
  31456. defines.push("#define BASIC_RENDER");
  31457. defines.push("#define NEED_UV");
  31458. needUV = true;
  31459. }
  31460. // Alpha test
  31461. if (material) {
  31462. if (material.needAlphaTesting() || mesh === this.mesh)
  31463. defines.push("#define ALPHATEST");
  31464. if (material.opacityTexture !== undefined) {
  31465. defines.push("#define OPACITY");
  31466. if (material.opacityTexture.getAlphaFromRGB)
  31467. defines.push("#define OPACITYRGB");
  31468. if (!needUV)
  31469. defines.push("#define NEED_UV");
  31470. }
  31471. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31472. attribs.push(BABYLON.VertexBuffer.UVKind);
  31473. defines.push("#define UV1");
  31474. }
  31475. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31476. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31477. defines.push("#define UV2");
  31478. }
  31479. }
  31480. // Bones
  31481. if (mesh.useBones) {
  31482. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31483. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31484. defines.push("#define BONES");
  31485. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31486. }
  31487. // Instances
  31488. if (useInstances) {
  31489. defines.push("#define INSTANCES");
  31490. attribs.push("world0");
  31491. attribs.push("world1");
  31492. attribs.push("world2");
  31493. attribs.push("world3");
  31494. }
  31495. // Get correct effect
  31496. var join = defines.join("\n");
  31497. if (this._cachedDefines !== join) {
  31498. this._cachedDefines = join;
  31499. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  31500. }
  31501. return this._volumetricLightScatteringPass.isReady();
  31502. };
  31503. /**
  31504. * Sets the new light position for light scattering effect
  31505. * @param {BABYLON.Vector3} The new custom light position
  31506. */
  31507. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  31508. this._customMeshPosition = position;
  31509. };
  31510. /**
  31511. * Returns the light position for light scattering effect
  31512. * @return {BABYLON.Vector3} The custom light position
  31513. */
  31514. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  31515. return this._customMeshPosition;
  31516. };
  31517. /**
  31518. * Disposes the internal assets and detaches the post-process from the camera
  31519. */
  31520. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  31521. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  31522. if (rttIndex !== -1) {
  31523. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  31524. }
  31525. this._volumetricLightScatteringRTT.dispose();
  31526. _super.prototype.dispose.call(this, camera);
  31527. };
  31528. /**
  31529. * Returns the render target texture used by the post-process
  31530. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  31531. */
  31532. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  31533. return this._volumetricLightScatteringRTT;
  31534. };
  31535. // Private methods
  31536. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31537. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31538. return true;
  31539. }
  31540. return false;
  31541. };
  31542. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31543. var _this = this;
  31544. var engine = scene.getEngine();
  31545. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31546. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31547. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31548. this._volumetricLightScatteringRTT.renderList = null;
  31549. this._volumetricLightScatteringRTT.renderParticles = false;
  31550. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31551. // Custom render function for submeshes
  31552. var renderSubMesh = function (subMesh) {
  31553. var mesh = subMesh.getRenderingMesh();
  31554. if (_this._meshExcluded(mesh)) {
  31555. return;
  31556. }
  31557. var scene = mesh.getScene();
  31558. var engine = scene.getEngine();
  31559. // Culling
  31560. engine.setState(subMesh.getMaterial().backFaceCulling);
  31561. // Managing instances
  31562. var batch = mesh._getInstancesRenderList(subMesh._id);
  31563. if (batch.mustReturn) {
  31564. return;
  31565. }
  31566. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31567. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31568. engine.enableEffect(_this._volumetricLightScatteringPass);
  31569. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31570. var material = subMesh.getMaterial();
  31571. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31572. // Alpha test
  31573. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31574. var alphaTexture = material.getAlphaTestTexture();
  31575. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31576. if (alphaTexture) {
  31577. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31578. }
  31579. if (material.opacityTexture !== undefined) {
  31580. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31581. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31582. }
  31583. }
  31584. // Bones
  31585. if (mesh.useBones) {
  31586. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31587. }
  31588. // Draw
  31589. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31590. }
  31591. };
  31592. // Render target texture callbacks
  31593. var savedSceneClearColor;
  31594. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31595. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31596. savedSceneClearColor = scene.clearColor;
  31597. scene.clearColor = sceneClearColor;
  31598. };
  31599. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31600. scene.clearColor = savedSceneClearColor;
  31601. };
  31602. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31603. var engine = scene.getEngine();
  31604. var index;
  31605. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31606. renderSubMesh(opaqueSubMeshes.data[index]);
  31607. }
  31608. engine.setAlphaTesting(true);
  31609. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31610. renderSubMesh(alphaTestSubMeshes.data[index]);
  31611. }
  31612. engine.setAlphaTesting(false);
  31613. if (transparentSubMeshes.length) {
  31614. // Sort sub meshes
  31615. for (index = 0; index < transparentSubMeshes.length; index++) {
  31616. var submesh = transparentSubMeshes.data[index];
  31617. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31618. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31619. }
  31620. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31621. sortedArray.sort(function (a, b) {
  31622. // Alpha index first
  31623. if (a._alphaIndex > b._alphaIndex) {
  31624. return 1;
  31625. }
  31626. if (a._alphaIndex < b._alphaIndex) {
  31627. return -1;
  31628. }
  31629. // Then distance to camera
  31630. if (a._distanceToCamera < b._distanceToCamera) {
  31631. return 1;
  31632. }
  31633. if (a._distanceToCamera > b._distanceToCamera) {
  31634. return -1;
  31635. }
  31636. return 0;
  31637. });
  31638. // Render sub meshes
  31639. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31640. for (index = 0; index < sortedArray.length; index++) {
  31641. renderSubMesh(sortedArray[index]);
  31642. }
  31643. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31644. }
  31645. };
  31646. };
  31647. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31648. var transform = scene.getTransformMatrix();
  31649. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31650. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31651. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31652. if (this.invert)
  31653. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31654. };
  31655. // Static methods
  31656. /**
  31657. * Creates a default mesh for the Volumeric Light Scattering post-process
  31658. * @param {string} The mesh name
  31659. * @param {BABYLON.Scene} The scene where to create the mesh
  31660. * @return {BABYLON.Mesh} the default mesh
  31661. */
  31662. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31663. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31664. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31665. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31666. return mesh;
  31667. };
  31668. return VolumetricLightScatteringPostProcess;
  31669. })(BABYLON.PostProcess);
  31670. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31671. })(BABYLON || (BABYLON = {}));
  31672. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31673. var __extends = this.__extends || function (d, b) {
  31674. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31675. function __() { this.constructor = d; }
  31676. __.prototype = b.prototype;
  31677. d.prototype = new __();
  31678. };
  31679. var BABYLON;
  31680. (function (BABYLON) {
  31681. var LensRenderingPipeline = (function (_super) {
  31682. __extends(LensRenderingPipeline, _super);
  31683. /**
  31684. * @constructor
  31685. *
  31686. * Effect parameters are as follow:
  31687. * {
  31688. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31689. * edge_blur: number; // from 0 to x (1 for realism)
  31690. * distortion: number; // from 0 to x (1 for realism)
  31691. * grain_amount: number; // from 0 to 1
  31692. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31693. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  31694. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31695. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31696. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  31697. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  31698. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31699. * }
  31700. * Note: if an effect parameter is unset, effect is disabled
  31701. *
  31702. * @param {string} name - The rendering pipeline name
  31703. * @param {object} parameters - An object containing all parameters (see above)
  31704. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31705. * @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)
  31706. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31707. */
  31708. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31709. var _this = this;
  31710. if (ratio === void 0) { ratio = 1.0; }
  31711. _super.call(this, scene.getEngine(), name);
  31712. // Lens effects can be of the following:
  31713. // - chromatic aberration (slight shift of RGB colors)
  31714. // - blur on the edge of the lens
  31715. // - lens distortion
  31716. // - depth-of-field blur & highlights enhancing
  31717. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31718. // - grain effect (noise or custom texture)
  31719. // Two additional texture samplers are needed:
  31720. // - depth map (for depth-of-field)
  31721. // - grain texture
  31722. /**
  31723. * The chromatic aberration PostProcess id in the pipeline
  31724. * @type {string}
  31725. */
  31726. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31727. /**
  31728. * The highlights enhancing PostProcess id in the pipeline
  31729. * @type {string}
  31730. */
  31731. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31732. /**
  31733. * The depth-of-field PostProcess id in the pipeline
  31734. * @type {string}
  31735. */
  31736. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31737. this._scene = scene;
  31738. // Fetch texture samplers
  31739. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31740. if (parameters.grain_texture) {
  31741. this._grainTexture = parameters.grain_texture;
  31742. }
  31743. else {
  31744. this._createGrainTexture();
  31745. }
  31746. // save parameters
  31747. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31748. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31749. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31750. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31751. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31752. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31753. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  31754. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31755. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31756. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31757. // Create effects
  31758. this._createChromaticAberrationPostProcess(ratio);
  31759. this._createHighlightsPostProcess(ratio);
  31760. this._createDepthOfFieldPostProcess(ratio);
  31761. // Set up pipeline
  31762. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  31763. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  31764. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  31765. if (this._highlightsGain == -1) {
  31766. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31767. }
  31768. // Finish
  31769. scene.postProcessRenderPipelineManager.addPipeline(this);
  31770. if (cameras) {
  31771. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31772. }
  31773. }
  31774. // public methods (self explanatory)
  31775. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  31776. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  31777. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  31778. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  31779. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  31780. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  31781. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  31782. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  31783. LensRenderingPipeline.prototype.setFocusDepth = function (amount) { this._dofDepth = amount; };
  31784. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDepth = -1; };
  31785. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  31786. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  31787. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  31788. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  31789. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  31790. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31791. this._highlightsGain = amount;
  31792. };
  31793. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31794. if (this._highlightsGain == -1) {
  31795. this._highlightsGain = 1.0;
  31796. }
  31797. this._highlightsThreshold = amount;
  31798. };
  31799. LensRenderingPipeline.prototype.disableHighlights = function () {
  31800. this._highlightsGain = -1;
  31801. };
  31802. /**
  31803. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31804. */
  31805. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31806. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31807. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31808. this._chromaticAberrationPostProcess = undefined;
  31809. this._highlightsPostProcess = undefined;
  31810. this._depthOfFieldPostProcess = undefined;
  31811. this._grainTexture.dispose();
  31812. if (disableDepthRender)
  31813. this._scene.disableDepthRenderer();
  31814. };
  31815. // colors shifting and distortion
  31816. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31817. var _this = this;
  31818. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31819. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31820. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31821. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31822. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31823. };
  31824. };
  31825. // highlights enhancing
  31826. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31827. var _this = this;
  31828. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31829. this._highlightsPostProcess.onApply = function (effect) {
  31830. effect.setFloat('gain', _this._highlightsGain);
  31831. effect.setFloat('threshold', _this._highlightsThreshold);
  31832. effect.setBool('pentagon', _this._dofPentagon);
  31833. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31834. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31835. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31836. };
  31837. };
  31838. // colors shifting and distortion
  31839. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31840. var _this = this;
  31841. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31842. "focus_depth", "aperture", "pentagon", "maxZ", "edge_blur", "chromatic_aberration",
  31843. "distortion", "blur_noise", "grain_amount", "screen_width", "screen_height", "highlights"
  31844. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31845. this._depthOfFieldPostProcess.onApply = function (effect) {
  31846. effect.setBool('blur_noise', _this._blurNoise);
  31847. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  31848. effect.setFloat('grain_amount', _this._grainAmount);
  31849. effect.setTexture("depthSampler", _this._depthTexture);
  31850. effect.setTexture("grainSampler", _this._grainTexture);
  31851. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31852. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31853. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31854. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31855. effect.setFloat('distortion', _this._distortion);
  31856. effect.setFloat('focus_depth', _this._dofDepth);
  31857. effect.setFloat('aperture', _this._dofAperture);
  31858. effect.setFloat('edge_blur', _this._edgeBlur);
  31859. effect.setBool('highlights', (_this._highlightsGain != -1));
  31860. };
  31861. };
  31862. // creates a black and white random noise texture, 512x512
  31863. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31864. var size = 512;
  31865. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31866. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31867. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31868. var context = this._grainTexture.getContext();
  31869. var rand = function (min, max) {
  31870. return Math.random() * (max - min) + min;
  31871. };
  31872. var value;
  31873. for (var x = 0; x < size; x++) {
  31874. for (var y = 0; y < size; y++) {
  31875. value = Math.floor(rand(0.42, 0.58) * 255);
  31876. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31877. context.fillRect(x, y, 1, 1);
  31878. }
  31879. }
  31880. this._grainTexture.update(false);
  31881. };
  31882. return LensRenderingPipeline;
  31883. })(BABYLON.PostProcessRenderPipeline);
  31884. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31885. })(BABYLON || (BABYLON = {}));
  31886. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31887. //
  31888. // This post-process allows the modification of rendered colors by using
  31889. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31890. //
  31891. // The object needs to be provided an url to a texture containing the color
  31892. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31893. // Use an image editing software to tweak the LUT to match your needs.
  31894. //
  31895. // For an example of a color LUT, see here:
  31896. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31897. // For explanations on color grading, see here:
  31898. // http://udn.epicgames.com/Three/ColorGrading.html
  31899. //
  31900. var __extends = this.__extends || function (d, b) {
  31901. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31902. function __() { this.constructor = d; }
  31903. __.prototype = b.prototype;
  31904. d.prototype = new __();
  31905. };
  31906. var BABYLON;
  31907. (function (BABYLON) {
  31908. var ColorCorrectionPostProcess = (function (_super) {
  31909. __extends(ColorCorrectionPostProcess, _super);
  31910. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31911. var _this = this;
  31912. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31913. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31914. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31915. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31916. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31917. this.onApply = function (effect) {
  31918. effect.setTexture("colorTable", _this._colorTableTexture);
  31919. };
  31920. }
  31921. return ColorCorrectionPostProcess;
  31922. })(BABYLON.PostProcess);
  31923. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31924. })(BABYLON || (BABYLON = {}));
  31925. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31926. var __extends = this.__extends || function (d, b) {
  31927. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31928. function __() { this.constructor = d; }
  31929. __.prototype = b.prototype;
  31930. d.prototype = new __();
  31931. };
  31932. var BABYLON;
  31933. (function (BABYLON) {
  31934. var StereogramFreeCamera = (function (_super) {
  31935. __extends(StereogramFreeCamera, _super);
  31936. function StereogramFreeCamera(name, position, eyeSpace, isVertical, scene) {
  31937. _super.call(this, name, position, scene);
  31938. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_VERTICAL_STEREOGRAM : BABYLON.Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM, eyeSpace);
  31939. }
  31940. return StereogramFreeCamera;
  31941. })(BABYLON.FreeCamera);
  31942. BABYLON.StereogramFreeCamera = StereogramFreeCamera;
  31943. var StereogramArcRotateCamera = (function (_super) {
  31944. __extends(StereogramArcRotateCamera, _super);
  31945. function StereogramArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, isVertical, scene) {
  31946. _super.call(this, name, alpha, beta, radius, target, scene);
  31947. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_VERTICAL_STEREOGRAM : BABYLON.Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM, eyeSpace);
  31948. }
  31949. return StereogramArcRotateCamera;
  31950. })(BABYLON.ArcRotateCamera);
  31951. BABYLON.StereogramArcRotateCamera = StereogramArcRotateCamera;
  31952. var StereogramGamepadCamera = (function (_super) {
  31953. __extends(StereogramGamepadCamera, _super);
  31954. function StereogramGamepadCamera(name, position, eyeSpace, isVertical, scene) {
  31955. _super.call(this, name, position, scene);
  31956. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_VERTICAL_STEREOGRAM : BABYLON.Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM, eyeSpace);
  31957. }
  31958. return StereogramGamepadCamera;
  31959. })(BABYLON.GamepadCamera);
  31960. BABYLON.StereogramGamepadCamera = StereogramGamepadCamera;
  31961. })(BABYLON || (BABYLON = {}));
  31962. //# sourceMappingURL=babylon.stereogramCamera.js.map
  31963. 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}","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","stereogramInterlacePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOGRAM_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\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","vrDistortionCorrectionPixelShader":"#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}","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}"};
  31964. 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 e=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=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,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!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i,r;if(r=e.subMeshes,i=r.length,!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;i>s;s++){var l=r[s];i>1&&!this.checkSubmeshCollision(l)||this.collideForSubMesh(l,o,t)}},e.prototype.collideForSubMesh=function(e,i,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(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){for(var i in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(e.updatedGeometries[i]);for(var r in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(r)&&this._collisionCache.addMesh(e.updatedMeshes[r]);var t={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};postMessage(t,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,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(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE: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={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.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}},t.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()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=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=r}(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 i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,o){return new i(this.x*t,this.y*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i){return i&&t.Tools.WithinEpsilon(this.x,i.x)&&t.Tools.WithinEpsilon(this.y,i.y)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},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},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},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);return new i(h,u)},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;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new i(r,s)},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,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m;return new i(f,x)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n;return new i(r,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,o){var n=t.x<o.x?t.x:o.x,r=t.y<o.y?t.y:o.y;return new i(n,r)},i.Maximize=function(t,o){var n=t.x>o.x?t.x:o.x,r=t.y>o.y?t.y:o.y;return new i(n,r)},i.Transform=function(t,o){var n=t.x*o.m[0]+t.y*o.m[4],r=t.x*o.m[1]+t.y*o.m[5];return new i(n,r)},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;return o*o+n*n},i}();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 i&&t.Tools.WithinEpsilon(this.x,i.x)&&t.Tools.WithinEpsilon(this.y,i.y)&&t.Tools.WithinEpsilon(this.z,i.z)},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),l=SIMD.float32x4.load(n.m,8),m=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,l),m));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),l=.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,l)},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,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m,y=t.z*h+n.z*u+o.z*l+r.z*m;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,l=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),m=o.multiply(n).multiply(l);return i.TransformCoordinates(t,m)},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),l=o.x*h.m[3]+o.y*h.m[7]+o.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(l,1)&&(u=u.scale(1/l)),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.RotationFromAxis=function(o,n,r){var s,e,a,h=i.Normalize(o),u=(i.Normalize(n),i.Normalize(r)),l=f.X,m=f.Y,x=(f.Z,0),y=0,c=0,p=0,z=0,M=0,w=0,I=-1,d=(Math.PI,0),D=0;0==u.z?M=1:0==u.x?p=1:(w=u.z/u.x,p=-w*Math.sqrt(1/(1+w*w)),M=Math.sqrt(1/(1+w*w))),e=new i(p,z,M),a=i.Cross(u,e),s=i.Cross(h,e),i.Dot(u,s)<0&&(I=1),D=i.Dot(h,e),c=Math.acos(D)*I,i.Dot(e,l)<0&&(c=Math.PI+c,e=e.scaleInPlace(-1),a=a.scaleInPlace(-1),d++);var S,v;return p=0,z=0,M=0,I=-1,0==u.z?p=1:(w=e.z/e.x,p=-w*Math.sqrt(1/(1+w*w)),M=Math.sqrt(1/(1+w*w))),S=new t.Vector3(p,z,M),v=t.Vector3.Cross(S,e),s=t.Vector3.Cross(u,S),t.Vector3.Dot(e,s)<0&&(I=1),D=t.Vector3.Dot(u,S),y=Math.acos(D)*I,t.Vector3.Dot(v,m)<0&&(y=Math.PI+y,v=v.scaleInPlace(-1),S=S.scaleInPlace(-1),d++),I=-1,s=t.Vector3.Cross(l,e),t.Vector3.Dot(s,m)<0&&(I=1),D=t.Vector3.Dot(e,l),x=-Math.acos(D)*I,0>D&&2>d&&(x=Math.PI+x),new t.Vector3(y,x,c)},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,l=o*n,m=i*i,f=o*o,x=m+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-l),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+l)):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],l=n[2],m=n[6],f=n[10],x=r+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(m-u)*o,i.y=(e-l)*o,i.z=(a-s)*o):r>h&&r>f?(o=2*Math.sqrt(1+r-h-f),i.w=(m-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+l)/o):h>f?(o=2*Math.sqrt(1+h-r-f),i.w=(e-l)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+m)/o):(o=2*Math.sqrt(1+f-r-h),i.w=(a-s)/o,i.x=(e+l)/o,i.y=(u+m)/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),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);n.x=f*u*h+m*l*a,n.y=m*l*h-f*u*a,n.z=f*l*a-m*u*h,n.w=f*l*h+m*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),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,r=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}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],l=this.m[9],m=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=m*p-f*c,M=l*p-f*y,w=l*c-m*y,I=u*p-f*x,d=u*c-m*x,D=u*y-l*x,S=e*z-a*M+h*w,v=-(s*z-a*I+h*d),g=s*M-e*I+h*D,T=-(s*w-e*d+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*m,q=e*f-h*l,V=e*m-a*l,E=s*f-h*u,Z=s*m-a*u,N=s*l-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*I+r*d)*R,t.m[9]=-(i*M-o*I+r*D)*R,t.m[13]=(i*w-o*d+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*V)*R,t.m[7]=(i*L-n*E+r*Z)*R,t.m[11]=-(i*q-o*E+r*N)*R,t.m[15]=(i*V-o*Z+n*N)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,s,e,a,h,u,l,m=this.m,f=t.m,x=SIMD.float32x4.load(m,0),y=SIMD.float32x4.load(m,4),c=SIMD.float32x4.load(m,8),p=SIMD.float32x4.load(m,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),l=SIMD.float32x4.mul(i,e),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,2,3,0,1),l),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,1,0,3,2),l),s=SIMD.float32x4.reciprocalApproximation(l),l=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(l,SIMD.float32x4.mul(s,s))),l=SIMD.float32x4.swizzle(l,0,0,0,0),e=SIMD.float32x4.mul(l,e),a=SIMD.float32x4.mul(l,a),h=SIMD.float32x4.mul(l,h),u=SIMD.float32x4.mul(l,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],l=this.m[7],m=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],I=t.m[1],d=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*I+r*v+s*_+e*P,i[o+2]=n*d+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+l*F,i[o+5]=a*I+h*v+u*_+l*P,i[o+6]=a*d+h*g+u*b+l*C,i[o+7]=a*D+h*T+u*A+l*L,i[o+8]=m*w+f*S+x*R+y*F,i[o+9]=m*I+f*v+x*_+y*P,i[o+10]=m*d+f*g+x*b+y*C,i[o+11]=m*D+f*T+x*A+y*L,i[o+12]=c*w+p*S+z*R+M*F,i[o+13]=c*I+p*v+z*_+M*P,i[o+14]=c*d+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 l=SIMD.float32x4.load(n,4);SIMD.float32x4.store(i,o+4,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 m=SIMD.float32x4.load(n,8);SIMD.float32x4.store(i,o+8,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 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]);\n\n},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,l,m,f,x,y,c,p){p.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]=l,p.m[11]=m,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,l,m,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]=l,z.m[10]=m,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 l=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(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);l=SIMD.float32x4.neg(l);var x=SIMD.float32x4.shuffle(l,m,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(l,m,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),I=SIMD.float32x4(0,1,0,0),d=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(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,8,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,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,l=t.y,m=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+l,s,1);return o.multiply(n).multiply(r).multiply(m)},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],l=n*o.m[8]+r*o.m[9]+s*o.m[10]+e*o.m[11],m=n*o.m[12]+r*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,l,m)},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,l=s*u-e*h,m=e*a-r*u,f=r*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return n=0!==x?1/x:0,this.normal.x=l*n,this.normal.y=m*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 l=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=l;var m=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),l=r.Unproject(new r(t,o,1),n,s,e,a,h),m=l.subtract(u);return m.normalize(),new i(u,m)},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=m,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 l=h*h,m=l*h,f=s*m+e*l+a*h,x=1/(3*s*l+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,c=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=c;var p=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=c.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=c.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=c.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),l-u>180&&(l-=360),-180>l-u&&(l+=360),this.orientation=0>u-h?y.CW:y.CCW,this.angle=c.FromDegrees(this.orientation===y.CW?h-l:l-h)}return t}();t.Arc2=p;var z=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=z;var M=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),l=new p(a,h,u),m=l.angle.radians()/e;l.orientation===y.CW&&(m*=-1);for(var f=l.startAngle.radians()+m,x=0;e>x;x++){var c=Math.cos(f)*l.radius+l.centerPoint.x,z=Math.sin(f)*l.radius+l.centerPoint.y;this.addLineTo(c,z),f+=m}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),l=u.length()+r;if(o>=r&&l>=o){var m=u.normalize(),f=o-r;return new n(a.x+m.x*f,a.y+m.y*f)}r=l}return t.Tools.Error(\"internal error\"),n.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=M;var w=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,l=1;i>l;l++)s=this._getLastNonNullVector(l),i-1>l&&(e=this._getFirstNonNullVector(l),this._tangents[l]=s.add(e),this._tangents[l].normalize()),this._distances[l]=this._distances[l-1]+s.length(),a=this._tangents[l],h=this._normals[l-1],u=this._binormals[l-1],this._normals[l]=r.Cross(u,a),this._normals[l].normalize(),this._binormals[l]=r.Cross(a,this._normals[l]),this._binormals[l].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=w;var I=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=I;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 D=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=D;var S=a.prototype.multiplyToArray,v=a.prototype.invertToRef,g=a.LookAtLHToRef,T=r.TransformCoordinatesToRef,R=r.TransformCoordinatesFromFloatsToRef,_=function(){function i(){}return Object.defineProperty(i,\"IsEnabled\",{get:function(){return i._isEnabled},enumerable:!0,configurable:!0}),i.DisableSIMD=function(){a.prototype.multiplyToArray=S,a.prototype.invertToRef=v,a.LookAtLHToRef=g,r.TransformCoordinatesToRef=T,r.TransformCoordinatesFromFloatsToRef=R,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=_,void 0!==window.SIMD&&window.SIMD.float32x4&&window.SIMD.float32x4.swizzle&&_.EnableSIMD()}(BABYLON||(BABYLON={}));";