babylon.2.1-beta.debug.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Color3 = (function () {
  4. function Color3(r, g, b) {
  5. if (r === void 0) { r = 0; }
  6. if (g === void 0) { g = 0; }
  7. if (b === void 0) { b = 0; }
  8. this.r = r;
  9. this.g = g;
  10. this.b = b;
  11. }
  12. Color3.prototype.toString = function () {
  13. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  14. };
  15. // Operators
  16. Color3.prototype.toArray = function (array, index) {
  17. if (index === undefined) {
  18. index = 0;
  19. }
  20. array[index] = this.r;
  21. array[index + 1] = this.g;
  22. array[index + 2] = this.b;
  23. return this;
  24. };
  25. Color3.prototype.toColor4 = function (alpha) {
  26. if (alpha === void 0) { alpha = 1; }
  27. return new Color4(this.r, this.g, this.b, alpha);
  28. };
  29. Color3.prototype.asArray = function () {
  30. var result = [];
  31. this.toArray(result, 0);
  32. return result;
  33. };
  34. Color3.prototype.toLuminance = function () {
  35. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  36. };
  37. Color3.prototype.multiply = function (otherColor) {
  38. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  39. };
  40. Color3.prototype.multiplyToRef = function (otherColor, result) {
  41. result.r = this.r * otherColor.r;
  42. result.g = this.g * otherColor.g;
  43. result.b = this.b * otherColor.b;
  44. return this;
  45. };
  46. Color3.prototype.equals = function (otherColor) {
  47. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  48. };
  49. Color3.prototype.scale = function (scale) {
  50. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  51. };
  52. Color3.prototype.scaleToRef = function (scale, result) {
  53. result.r = this.r * scale;
  54. result.g = this.g * scale;
  55. result.b = this.b * scale;
  56. return this;
  57. };
  58. Color3.prototype.add = function (otherColor) {
  59. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  60. };
  61. Color3.prototype.addToRef = function (otherColor, result) {
  62. result.r = this.r + otherColor.r;
  63. result.g = this.g + otherColor.g;
  64. result.b = this.b + otherColor.b;
  65. return this;
  66. };
  67. Color3.prototype.subtract = function (otherColor) {
  68. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  69. };
  70. Color3.prototype.subtractToRef = function (otherColor, result) {
  71. result.r = this.r - otherColor.r;
  72. result.g = this.g - otherColor.g;
  73. result.b = this.b - otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.clone = function () {
  77. return new Color3(this.r, this.g, this.b);
  78. };
  79. Color3.prototype.copyFrom = function (source) {
  80. this.r = source.r;
  81. this.g = source.g;
  82. this.b = source.b;
  83. return this;
  84. };
  85. Color3.prototype.copyFromFloats = function (r, g, b) {
  86. this.r = r;
  87. this.g = g;
  88. this.b = b;
  89. return this;
  90. };
  91. // Statics
  92. Color3.FromArray = function (array, offset) {
  93. if (offset === void 0) { offset = 0; }
  94. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  95. };
  96. Color3.FromInts = function (r, g, b) {
  97. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  98. };
  99. Color3.Lerp = function (start, end, amount) {
  100. var r = start.r + ((end.r - start.r) * amount);
  101. var g = start.g + ((end.g - start.g) * amount);
  102. var b = start.b + ((end.b - start.b) * amount);
  103. return new Color3(r, g, b);
  104. };
  105. Color3.Red = function () {
  106. return new Color3(1, 0, 0);
  107. };
  108. Color3.Green = function () {
  109. return new Color3(0, 1, 0);
  110. };
  111. Color3.Blue = function () {
  112. return new Color3(0, 0, 1);
  113. };
  114. Color3.Black = function () {
  115. return new Color3(0, 0, 0);
  116. };
  117. Color3.White = function () {
  118. return new Color3(1, 1, 1);
  119. };
  120. Color3.Purple = function () {
  121. return new Color3(0.5, 0, 0.5);
  122. };
  123. Color3.Magenta = function () {
  124. return new Color3(1, 0, 1);
  125. };
  126. Color3.Yellow = function () {
  127. return new Color3(1, 1, 0);
  128. };
  129. Color3.Gray = function () {
  130. return new Color3(0.5, 0.5, 0.5);
  131. };
  132. return Color3;
  133. })();
  134. BABYLON.Color3 = Color3;
  135. var Color4 = (function () {
  136. function Color4(r, g, b, a) {
  137. this.r = r;
  138. this.g = g;
  139. this.b = b;
  140. this.a = a;
  141. }
  142. // Operators
  143. Color4.prototype.addInPlace = function (right) {
  144. this.r += right.r;
  145. this.g += right.g;
  146. this.b += right.b;
  147. this.a += right.a;
  148. return this;
  149. };
  150. Color4.prototype.asArray = function () {
  151. var result = [];
  152. this.toArray(result, 0);
  153. return result;
  154. };
  155. Color4.prototype.toArray = function (array, index) {
  156. if (index === undefined) {
  157. index = 0;
  158. }
  159. array[index] = this.r;
  160. array[index + 1] = this.g;
  161. array[index + 2] = this.b;
  162. array[index + 3] = this.a;
  163. return this;
  164. };
  165. Color4.prototype.add = function (right) {
  166. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  167. };
  168. Color4.prototype.subtract = function (right) {
  169. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  170. };
  171. Color4.prototype.subtractToRef = function (right, result) {
  172. result.r = this.r - right.r;
  173. result.g = this.g - right.g;
  174. result.b = this.b - right.b;
  175. result.a = this.a - right.a;
  176. return this;
  177. };
  178. Color4.prototype.scale = function (scale) {
  179. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  180. };
  181. Color4.prototype.scaleToRef = function (scale, result) {
  182. result.r = this.r * scale;
  183. result.g = this.g * scale;
  184. result.b = this.b * scale;
  185. result.a = this.a * scale;
  186. return this;
  187. };
  188. Color4.prototype.toString = function () {
  189. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  190. };
  191. Color4.prototype.clone = function () {
  192. return new Color4(this.r, this.g, this.b, this.a);
  193. };
  194. Color4.prototype.copyFrom = function (source) {
  195. this.r = source.r;
  196. this.g = source.g;
  197. this.b = source.b;
  198. this.a = source.a;
  199. return this;
  200. };
  201. // Statics
  202. Color4.Lerp = function (left, right, amount) {
  203. var result = new Color4(0, 0, 0, 0);
  204. Color4.LerpToRef(left, right, amount, result);
  205. return result;
  206. };
  207. Color4.LerpToRef = function (left, right, amount, result) {
  208. result.r = left.r + (right.r - left.r) * amount;
  209. result.g = left.g + (right.g - left.g) * amount;
  210. result.b = left.b + (right.b - left.b) * amount;
  211. result.a = left.a + (right.a - left.a) * amount;
  212. };
  213. Color4.FromArray = function (array, offset) {
  214. if (offset === void 0) { offset = 0; }
  215. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  216. };
  217. Color4.FromInts = function (r, g, b, a) {
  218. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  219. };
  220. return Color4;
  221. })();
  222. BABYLON.Color4 = Color4;
  223. var Vector2 = (function () {
  224. function Vector2(x, y) {
  225. this.x = x;
  226. this.y = y;
  227. }
  228. Vector2.prototype.toString = function () {
  229. return "{X: " + this.x + " Y:" + this.y + "}";
  230. };
  231. // Operators
  232. Vector2.prototype.toArray = function (array, index) {
  233. if (index === void 0) { index = 0; }
  234. array[index] = this.x;
  235. array[index + 1] = this.y;
  236. return this;
  237. };
  238. Vector2.prototype.asArray = function () {
  239. var result = [];
  240. this.toArray(result, 0);
  241. return result;
  242. };
  243. Vector2.prototype.copyFrom = function (source) {
  244. this.x = source.x;
  245. this.y = source.y;
  246. return this;
  247. };
  248. Vector2.prototype.copyFromFloats = function (x, y) {
  249. this.x = x;
  250. this.y = y;
  251. return this;
  252. };
  253. Vector2.prototype.add = function (otherVector) {
  254. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  255. };
  256. Vector2.prototype.addVector3 = function (otherVector) {
  257. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  258. };
  259. Vector2.prototype.subtract = function (otherVector) {
  260. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  261. };
  262. Vector2.prototype.subtractInPlace = function (otherVector) {
  263. this.x -= otherVector.x;
  264. this.y -= otherVector.y;
  265. return this;
  266. };
  267. Vector2.prototype.multiplyInPlace = function (otherVector) {
  268. this.x *= otherVector.x;
  269. this.y *= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiply = function (otherVector) {
  273. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  274. };
  275. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  276. result.x = this.x * otherVector.x;
  277. result.y = this.y * otherVector.y;
  278. return this;
  279. };
  280. Vector2.prototype.multiplyByFloats = function (x, y) {
  281. return new Vector2(this.x * x, this.y * y);
  282. };
  283. Vector2.prototype.divide = function (otherVector) {
  284. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  285. };
  286. Vector2.prototype.divideToRef = function (otherVector, result) {
  287. result.x = this.x / otherVector.x;
  288. result.y = this.y / otherVector.y;
  289. return this;
  290. };
  291. Vector2.prototype.negate = function () {
  292. return new Vector2(-this.x, -this.y);
  293. };
  294. Vector2.prototype.scaleInPlace = function (scale) {
  295. this.x *= scale;
  296. this.y *= scale;
  297. return this;
  298. };
  299. Vector2.prototype.scale = function (scale) {
  300. return new Vector2(this.x * scale, this.y * scale);
  301. };
  302. Vector2.prototype.equals = function (otherVector) {
  303. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  304. };
  305. Vector2.prototype.equalsWithEpsilon = function (otherVector) {
  306. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y);
  307. };
  308. // Properties
  309. Vector2.prototype.length = function () {
  310. return Math.sqrt(this.x * this.x + this.y * this.y);
  311. };
  312. Vector2.prototype.lengthSquared = function () {
  313. return (this.x * this.x + this.y * this.y);
  314. };
  315. // Methods
  316. Vector2.prototype.normalize = function () {
  317. var len = this.length();
  318. if (len === 0)
  319. return this;
  320. var num = 1.0 / len;
  321. this.x *= num;
  322. this.y *= num;
  323. return this;
  324. };
  325. Vector2.prototype.clone = function () {
  326. return new Vector2(this.x, this.y);
  327. };
  328. // Statics
  329. Vector2.Zero = function () {
  330. return new Vector2(0, 0);
  331. };
  332. Vector2.FromArray = function (array, offset) {
  333. if (offset === void 0) { offset = 0; }
  334. return new Vector2(array[offset], array[offset + 1]);
  335. };
  336. Vector2.FromArrayToRef = function (array, offset, result) {
  337. result.x = array[offset];
  338. result.y = array[offset + 1];
  339. };
  340. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  341. var squared = amount * amount;
  342. var cubed = amount * squared;
  343. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  344. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  345. return new Vector2(x, y);
  346. };
  347. Vector2.Clamp = function (value, min, max) {
  348. var x = value.x;
  349. x = (x > max.x) ? max.x : x;
  350. x = (x < min.x) ? min.x : x;
  351. var y = value.y;
  352. y = (y > max.y) ? max.y : y;
  353. y = (y < min.y) ? min.y : y;
  354. return new Vector2(x, y);
  355. };
  356. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  357. var squared = amount * amount;
  358. var cubed = amount * squared;
  359. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  360. var part2 = (-2.0 * cubed) + (3.0 * squared);
  361. var part3 = (cubed - (2.0 * squared)) + amount;
  362. var part4 = cubed - squared;
  363. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  364. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  365. return new Vector2(x, y);
  366. };
  367. Vector2.Lerp = function (start, end, amount) {
  368. var x = start.x + ((end.x - start.x) * amount);
  369. var y = start.y + ((end.y - start.y) * amount);
  370. return new Vector2(x, y);
  371. };
  372. Vector2.Dot = function (left, right) {
  373. return left.x * right.x + left.y * right.y;
  374. };
  375. Vector2.Normalize = function (vector) {
  376. var newVector = vector.clone();
  377. newVector.normalize();
  378. return newVector;
  379. };
  380. Vector2.Minimize = function (left, right) {
  381. var x = (left.x < right.x) ? left.x : right.x;
  382. var y = (left.y < right.y) ? left.y : right.y;
  383. return new Vector2(x, y);
  384. };
  385. Vector2.Maximize = function (left, right) {
  386. var x = (left.x > right.x) ? left.x : right.x;
  387. var y = (left.y > right.y) ? left.y : right.y;
  388. return new Vector2(x, y);
  389. };
  390. Vector2.Transform = function (vector, transformation) {
  391. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  392. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  393. return new Vector2(x, y);
  394. };
  395. Vector2.Distance = function (value1, value2) {
  396. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  397. };
  398. Vector2.DistanceSquared = function (value1, value2) {
  399. var x = value1.x - value2.x;
  400. var y = value1.y - value2.y;
  401. return (x * x) + (y * y);
  402. };
  403. return Vector2;
  404. })();
  405. BABYLON.Vector2 = Vector2;
  406. var Vector3 = (function () {
  407. function Vector3(x, y, z) {
  408. this.x = x;
  409. this.y = y;
  410. this.z = z;
  411. }
  412. Vector3.prototype.toString = function () {
  413. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  414. };
  415. // Operators
  416. Vector3.prototype.asArray = function () {
  417. var result = [];
  418. this.toArray(result, 0);
  419. return result;
  420. };
  421. Vector3.prototype.toArray = function (array, index) {
  422. if (index === void 0) { index = 0; }
  423. array[index] = this.x;
  424. array[index + 1] = this.y;
  425. array[index + 2] = this.z;
  426. return this;
  427. };
  428. Vector3.prototype.toQuaternion = function () {
  429. var result = new Quaternion(0, 0, 0, 1);
  430. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  431. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  432. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  433. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  434. var cosy = Math.cos(this.y * 0.5);
  435. var siny = Math.sin(this.y * 0.5);
  436. result.x = coszMinusx * siny;
  437. result.y = -sinzMinusx * siny;
  438. result.z = sinxPlusz * cosy;
  439. result.w = cosxPlusz * cosy;
  440. return result;
  441. };
  442. Vector3.prototype.addInPlace = function (otherVector) {
  443. this.x += otherVector.x;
  444. this.y += otherVector.y;
  445. this.z += otherVector.z;
  446. return this;
  447. };
  448. Vector3.prototype.add = function (otherVector) {
  449. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  450. };
  451. Vector3.prototype.addToRef = function (otherVector, result) {
  452. result.x = this.x + otherVector.x;
  453. result.y = this.y + otherVector.y;
  454. result.z = this.z + otherVector.z;
  455. return this;
  456. };
  457. Vector3.prototype.subtractInPlace = function (otherVector) {
  458. this.x -= otherVector.x;
  459. this.y -= otherVector.y;
  460. this.z -= otherVector.z;
  461. return this;
  462. };
  463. Vector3.prototype.subtract = function (otherVector) {
  464. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  465. };
  466. Vector3.prototype.subtractToRef = function (otherVector, result) {
  467. result.x = this.x - otherVector.x;
  468. result.y = this.y - otherVector.y;
  469. result.z = this.z - otherVector.z;
  470. return this;
  471. };
  472. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  473. return new Vector3(this.x - x, this.y - y, this.z - z);
  474. };
  475. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  476. result.x = this.x - x;
  477. result.y = this.y - y;
  478. result.z = this.z - z;
  479. return this;
  480. };
  481. Vector3.prototype.negate = function () {
  482. return new Vector3(-this.x, -this.y, -this.z);
  483. };
  484. Vector3.prototype.scaleInPlace = function (scale) {
  485. this.x *= scale;
  486. this.y *= scale;
  487. this.z *= scale;
  488. return this;
  489. };
  490. Vector3.prototype.scale = function (scale) {
  491. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  492. };
  493. Vector3.prototype.scaleToRef = function (scale, result) {
  494. result.x = this.x * scale;
  495. result.y = this.y * scale;
  496. result.z = this.z * scale;
  497. };
  498. Vector3.prototype.equals = function (otherVector) {
  499. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  500. };
  501. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  502. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z);
  503. };
  504. Vector3.prototype.equalsToFloats = function (x, y, z) {
  505. return this.x === x && this.y === y && this.z === z;
  506. };
  507. Vector3.prototype.multiplyInPlace = function (otherVector) {
  508. this.x *= otherVector.x;
  509. this.y *= otherVector.y;
  510. this.z *= otherVector.z;
  511. return this;
  512. };
  513. Vector3.prototype.multiply = function (otherVector) {
  514. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  515. };
  516. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  517. result.x = this.x * otherVector.x;
  518. result.y = this.y * otherVector.y;
  519. result.z = this.z * otherVector.z;
  520. return this;
  521. };
  522. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  523. return new Vector3(this.x * x, this.y * y, this.z * z);
  524. };
  525. Vector3.prototype.divide = function (otherVector) {
  526. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  527. };
  528. Vector3.prototype.divideToRef = function (otherVector, result) {
  529. result.x = this.x / otherVector.x;
  530. result.y = this.y / otherVector.y;
  531. result.z = this.z / otherVector.z;
  532. return this;
  533. };
  534. Vector3.prototype.MinimizeInPlace = function (other) {
  535. if (other.x < this.x)
  536. this.x = other.x;
  537. if (other.y < this.y)
  538. this.y = other.y;
  539. if (other.z < this.z)
  540. this.z = other.z;
  541. return this;
  542. };
  543. Vector3.prototype.MaximizeInPlace = function (other) {
  544. if (other.x > this.x)
  545. this.x = other.x;
  546. if (other.y > this.y)
  547. this.y = other.y;
  548. if (other.z > this.z)
  549. this.z = other.z;
  550. return this;
  551. };
  552. // Properties
  553. Vector3.prototype.length = function () {
  554. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  555. };
  556. Vector3.prototype.lengthSquared = function () {
  557. return (this.x * this.x + this.y * this.y + this.z * this.z);
  558. };
  559. // Methods
  560. Vector3.prototype.normalize = function () {
  561. var len = this.length();
  562. if (len === 0)
  563. return this;
  564. var num = 1.0 / len;
  565. this.x *= num;
  566. this.y *= num;
  567. this.z *= num;
  568. return this;
  569. };
  570. Vector3.prototype.clone = function () {
  571. return new Vector3(this.x, this.y, this.z);
  572. };
  573. Vector3.prototype.copyFrom = function (source) {
  574. this.x = source.x;
  575. this.y = source.y;
  576. this.z = source.z;
  577. return this;
  578. };
  579. Vector3.prototype.copyFromFloats = function (x, y, z) {
  580. this.x = x;
  581. this.y = y;
  582. this.z = z;
  583. return this;
  584. };
  585. // Statics
  586. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  587. var d0 = Vector3.Dot(vector0, axis) - size;
  588. var d1 = Vector3.Dot(vector1, axis) - size;
  589. var s = d0 / (d0 - d1);
  590. return s;
  591. };
  592. Vector3.FromArray = function (array, offset) {
  593. if (!offset) {
  594. offset = 0;
  595. }
  596. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  597. };
  598. Vector3.FromArrayToRef = function (array, offset, result) {
  599. result.x = array[offset];
  600. result.y = array[offset + 1];
  601. result.z = array[offset + 2];
  602. };
  603. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  604. result.x = array[offset];
  605. result.y = array[offset + 1];
  606. result.z = array[offset + 2];
  607. };
  608. Vector3.FromFloatsToRef = function (x, y, z, result) {
  609. result.x = x;
  610. result.y = y;
  611. result.z = z;
  612. };
  613. Vector3.Zero = function () {
  614. return new Vector3(0, 0, 0);
  615. };
  616. Vector3.Up = function () {
  617. return new Vector3(0, 1.0, 0);
  618. };
  619. Vector3.TransformCoordinates = function (vector, transformation) {
  620. var result = Vector3.Zero();
  621. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  622. return result;
  623. };
  624. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  625. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  626. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  627. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  628. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  629. result.x = x / w;
  630. result.y = y / w;
  631. result.z = z / w;
  632. };
  633. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  634. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  635. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  636. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  637. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  638. result.x = rx / rw;
  639. result.y = ry / rw;
  640. result.z = rz / rw;
  641. };
  642. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  643. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  644. var m0 = SIMD.float32x4.load(transformation.m, 0);
  645. var m1 = SIMD.float32x4.load(transformation.m, 4);
  646. var m2 = SIMD.float32x4.load(transformation.m, 8);
  647. var m3 = SIMD.float32x4.load(transformation.m, 12);
  648. 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));
  649. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  650. SIMD.float32x4.storeXYZ(result._data, 0, r);
  651. };
  652. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  653. var v0 = SIMD.float32x4.splat(x);
  654. var v1 = SIMD.float32x4.splat(y);
  655. var v2 = SIMD.float32x4.splat(z);
  656. var m0 = SIMD.float32x4.load(transformation.m, 0);
  657. var m1 = SIMD.float32x4.load(transformation.m, 4);
  658. var m2 = SIMD.float32x4.load(transformation.m, 8);
  659. var m3 = SIMD.float32x4.load(transformation.m, 12);
  660. 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));
  661. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  662. SIMD.float32x4.storeXYZ(result._data, 0, r);
  663. };
  664. Vector3.TransformNormal = function (vector, transformation) {
  665. var result = Vector3.Zero();
  666. Vector3.TransformNormalToRef(vector, transformation, result);
  667. return result;
  668. };
  669. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  670. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  671. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  672. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  673. };
  674. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  675. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  676. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  677. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  678. };
  679. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  680. var squared = amount * amount;
  681. var cubed = amount * squared;
  682. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  683. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  684. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  685. return new Vector3(x, y, z);
  686. };
  687. Vector3.Clamp = function (value, min, max) {
  688. var x = value.x;
  689. x = (x > max.x) ? max.x : x;
  690. x = (x < min.x) ? min.x : x;
  691. var y = value.y;
  692. y = (y > max.y) ? max.y : y;
  693. y = (y < min.y) ? min.y : y;
  694. var z = value.z;
  695. z = (z > max.z) ? max.z : z;
  696. z = (z < min.z) ? min.z : z;
  697. return new Vector3(x, y, z);
  698. };
  699. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  700. var squared = amount * amount;
  701. var cubed = amount * squared;
  702. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  703. var part2 = (-2.0 * cubed) + (3.0 * squared);
  704. var part3 = (cubed - (2.0 * squared)) + amount;
  705. var part4 = cubed - squared;
  706. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  707. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  708. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  709. return new Vector3(x, y, z);
  710. };
  711. Vector3.Lerp = function (start, end, amount) {
  712. var x = start.x + ((end.x - start.x) * amount);
  713. var y = start.y + ((end.y - start.y) * amount);
  714. var z = start.z + ((end.z - start.z) * amount);
  715. return new Vector3(x, y, z);
  716. };
  717. Vector3.Dot = function (left, right) {
  718. return (left.x * right.x + left.y * right.y + left.z * right.z);
  719. };
  720. Vector3.Cross = function (left, right) {
  721. var result = Vector3.Zero();
  722. Vector3.CrossToRef(left, right, result);
  723. return result;
  724. };
  725. Vector3.CrossToRef = function (left, right, result) {
  726. result.x = left.y * right.z - left.z * right.y;
  727. result.y = left.z * right.x - left.x * right.z;
  728. result.z = left.x * right.y - left.y * right.x;
  729. };
  730. Vector3.Normalize = function (vector) {
  731. var result = Vector3.Zero();
  732. Vector3.NormalizeToRef(vector, result);
  733. return result;
  734. };
  735. Vector3.NormalizeToRef = function (vector, result) {
  736. result.copyFrom(vector);
  737. result.normalize();
  738. };
  739. Vector3.Project = function (vector, world, transform, viewport) {
  740. var cw = viewport.width;
  741. var ch = viewport.height;
  742. var cx = viewport.x;
  743. var cy = viewport.y;
  744. 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);
  745. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  746. return Vector3.TransformCoordinates(vector, finalMatrix);
  747. };
  748. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  749. var matrix = world.multiply(transform);
  750. matrix.invert();
  751. source.x = source.x / viewportWidth * 2 - 1;
  752. source.y = -(source.y / viewportHeight * 2 - 1);
  753. var vector = Vector3.TransformCoordinates(source, matrix);
  754. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  755. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  756. vector = vector.scale(1.0 / num);
  757. }
  758. return vector;
  759. };
  760. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  761. var matrix = world.multiply(view).multiply(projection);
  762. matrix.invert();
  763. source.x = source.x / viewportWidth * 2 - 1;
  764. source.y = -(source.y / viewportHeight * 2 - 1);
  765. var vector = Vector3.TransformCoordinates(source, matrix);
  766. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  767. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  768. vector = vector.scale(1.0 / num);
  769. }
  770. return vector;
  771. };
  772. Vector3.Minimize = function (left, right) {
  773. var min = left.clone();
  774. min.MinimizeInPlace(right);
  775. return min;
  776. };
  777. Vector3.Maximize = function (left, right) {
  778. var max = left.clone();
  779. max.MaximizeInPlace(right);
  780. return max;
  781. };
  782. Vector3.Distance = function (value1, value2) {
  783. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  784. };
  785. Vector3.DistanceSquared = function (value1, value2) {
  786. var x = value1.x - value2.x;
  787. var y = value1.y - value2.y;
  788. var z = value1.z - value2.z;
  789. return (x * x) + (y * y) + (z * z);
  790. };
  791. Vector3.Center = function (value1, value2) {
  792. var center = value1.add(value2);
  793. center.scaleInPlace(0.5);
  794. return center;
  795. };
  796. /**
  797. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  798. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  799. * to something in order to rotate it from its local system to the given target system.
  800. */
  801. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  802. var u = Vector3.Normalize(axis1);
  803. var v = Vector3.Normalize(axis2);
  804. var w = Vector3.Normalize(axis3);
  805. // world axis
  806. var X = Axis.X;
  807. var Y = Axis.Y;
  808. var Z = Axis.Z;
  809. // equation unknowns and vars
  810. var yaw = 0.0;
  811. var pitch = 0.0;
  812. var roll = 0.0;
  813. var x = 0.0;
  814. var y = 0.0;
  815. var z = 0.0;
  816. var t = 0.0;
  817. var sign = -1.0;
  818. var pi = Math.PI;
  819. var nbRevert = 0;
  820. var cross;
  821. var dot = 0.0;
  822. // step 1 : rotation around w
  823. // Rv3(u) = u1, and u1 belongs to plane xOz
  824. // Rv3(w) = w1 = w invariant
  825. var u1;
  826. var v1;
  827. if (w.z == 0) {
  828. z = 1.0;
  829. }
  830. else if (w.x == 0) {
  831. x = 1.0;
  832. }
  833. else {
  834. t = w.z / w.x;
  835. x = -t * Math.sqrt(1 / (1 + t * t));
  836. z = Math.sqrt(1 / (1 + t * t));
  837. }
  838. u1 = new Vector3(x, y, z);
  839. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  840. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  841. if (Vector3.Dot(w, cross) < 0) {
  842. sign = 1;
  843. }
  844. dot = Vector3.Dot(u, u1);
  845. roll = Math.acos(dot) * sign;
  846. if (Vector3.Dot(u1, X) < 0) {
  847. roll = Math.PI + roll;
  848. u1 = u1.scaleInPlace(-1);
  849. v1 = v1.scaleInPlace(-1);
  850. nbRevert++;
  851. }
  852. // step 2 : rotate around u1
  853. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  854. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  855. var w2;
  856. var v2;
  857. x = 0.0;
  858. y = 0.0;
  859. z = 0.0;
  860. sign = -1;
  861. if (w.z == 0) {
  862. x = 1.0;
  863. }
  864. else {
  865. t = u1.z / u1.x;
  866. x = -t * Math.sqrt(1 / (1 + t * t));
  867. z = Math.sqrt(1 / (1 + t * t));
  868. }
  869. w2 = new BABYLON.Vector3(x, y, z);
  870. v2 = BABYLON.Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  871. cross = BABYLON.Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  872. if (BABYLON.Vector3.Dot(u1, cross) < 0) {
  873. sign = 1;
  874. }
  875. dot = BABYLON.Vector3.Dot(w, w2);
  876. pitch = Math.acos(dot) * sign;
  877. if (BABYLON.Vector3.Dot(v2, Y) < 0) {
  878. pitch = Math.PI + pitch;
  879. v2 = v2.scaleInPlace(-1);
  880. w2 = w2.scaleInPlace(-1);
  881. nbRevert++;
  882. }
  883. // step 3 : rotate around v2
  884. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  885. sign = -1;
  886. cross = BABYLON.Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  887. if (BABYLON.Vector3.Dot(cross, Y) < 0) {
  888. sign = 1;
  889. }
  890. dot = BABYLON.Vector3.Dot(u1, X);
  891. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  892. if (dot < 0 && nbRevert < 2) {
  893. yaw = Math.PI + yaw;
  894. }
  895. return new BABYLON.Vector3(pitch, yaw, roll);
  896. };
  897. return Vector3;
  898. })();
  899. BABYLON.Vector3 = Vector3;
  900. //Vector4 class created for EulerAngle class conversion to Quaternion
  901. var Vector4 = (function () {
  902. function Vector4(x, y, z, w) {
  903. this.x = x;
  904. this.y = y;
  905. this.z = z;
  906. this.w = w;
  907. }
  908. Vector4.prototype.toString = function () {
  909. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  910. };
  911. // Operators
  912. Vector4.prototype.asArray = function () {
  913. var result = [];
  914. this.toArray(result, 0);
  915. return result;
  916. };
  917. Vector4.prototype.toArray = function (array, index) {
  918. if (index === undefined) {
  919. index = 0;
  920. }
  921. array[index] = this.x;
  922. array[index + 1] = this.y;
  923. array[index + 2] = this.z;
  924. array[index + 3] = this.w;
  925. return this;
  926. };
  927. Vector4.prototype.addInPlace = function (otherVector) {
  928. this.x += otherVector.x;
  929. this.y += otherVector.y;
  930. this.z += otherVector.z;
  931. this.w += otherVector.w;
  932. return this;
  933. };
  934. Vector4.prototype.add = function (otherVector) {
  935. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  936. };
  937. Vector4.prototype.addToRef = function (otherVector, result) {
  938. result.x = this.x + otherVector.x;
  939. result.y = this.y + otherVector.y;
  940. result.z = this.z + otherVector.z;
  941. result.w = this.w + otherVector.w;
  942. return this;
  943. };
  944. Vector4.prototype.subtractInPlace = function (otherVector) {
  945. this.x -= otherVector.x;
  946. this.y -= otherVector.y;
  947. this.z -= otherVector.z;
  948. this.w -= otherVector.w;
  949. return this;
  950. };
  951. Vector4.prototype.subtract = function (otherVector) {
  952. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  953. };
  954. Vector4.prototype.subtractToRef = function (otherVector, result) {
  955. result.x = this.x - otherVector.x;
  956. result.y = this.y - otherVector.y;
  957. result.z = this.z - otherVector.z;
  958. result.w = this.w - otherVector.w;
  959. return this;
  960. };
  961. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  962. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  963. };
  964. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  965. result.x = this.x - x;
  966. result.y = this.y - y;
  967. result.z = this.z - z;
  968. result.w = this.w - w;
  969. return this;
  970. };
  971. Vector4.prototype.negate = function () {
  972. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  973. };
  974. Vector4.prototype.scaleInPlace = function (scale) {
  975. this.x *= scale;
  976. this.y *= scale;
  977. this.z *= scale;
  978. this.w *= scale;
  979. return this;
  980. };
  981. Vector4.prototype.scale = function (scale) {
  982. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  983. };
  984. Vector4.prototype.scaleToRef = function (scale, result) {
  985. result.x = this.x * scale;
  986. result.y = this.y * scale;
  987. result.z = this.z * scale;
  988. result.w = this.w * scale;
  989. };
  990. Vector4.prototype.equals = function (otherVector) {
  991. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  992. };
  993. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  994. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  995. };
  996. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  997. return this.x === x && this.y === y && this.z === z && this.w === w;
  998. };
  999. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1000. this.x *= otherVector.x;
  1001. this.y *= otherVector.y;
  1002. this.z *= otherVector.z;
  1003. this.w *= otherVector.w;
  1004. return this;
  1005. };
  1006. Vector4.prototype.multiply = function (otherVector) {
  1007. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1008. };
  1009. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1010. result.x = this.x * otherVector.x;
  1011. result.y = this.y * otherVector.y;
  1012. result.z = this.z * otherVector.z;
  1013. result.w = this.w * otherVector.w;
  1014. return this;
  1015. };
  1016. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1017. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1018. };
  1019. Vector4.prototype.divide = function (otherVector) {
  1020. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1021. };
  1022. Vector4.prototype.divideToRef = function (otherVector, result) {
  1023. result.x = this.x / otherVector.x;
  1024. result.y = this.y / otherVector.y;
  1025. result.z = this.z / otherVector.z;
  1026. result.w = this.w / otherVector.w;
  1027. return this;
  1028. };
  1029. Vector4.prototype.MinimizeInPlace = function (other) {
  1030. if (other.x < this.x)
  1031. this.x = other.x;
  1032. if (other.y < this.y)
  1033. this.y = other.y;
  1034. if (other.z < this.z)
  1035. this.z = other.z;
  1036. if (other.w < this.w)
  1037. this.w = other.w;
  1038. return this;
  1039. };
  1040. Vector4.prototype.MaximizeInPlace = function (other) {
  1041. if (other.x > this.x)
  1042. this.x = other.x;
  1043. if (other.y > this.y)
  1044. this.y = other.y;
  1045. if (other.z > this.z)
  1046. this.z = other.z;
  1047. if (other.w > this.w)
  1048. this.w = other.w;
  1049. return this;
  1050. };
  1051. // Properties
  1052. Vector4.prototype.length = function () {
  1053. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1054. };
  1055. Vector4.prototype.lengthSquared = function () {
  1056. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1057. };
  1058. // Methods
  1059. Vector4.prototype.normalize = function () {
  1060. var len = this.length();
  1061. if (len === 0)
  1062. return this;
  1063. var num = 1.0 / len;
  1064. this.x *= num;
  1065. this.y *= num;
  1066. this.z *= num;
  1067. this.w *= num;
  1068. return this;
  1069. };
  1070. Vector4.prototype.clone = function () {
  1071. return new Vector4(this.x, this.y, this.z, this.w);
  1072. };
  1073. Vector4.prototype.copyFrom = function (source) {
  1074. this.x = source.x;
  1075. this.y = source.y;
  1076. this.z = source.z;
  1077. this.w = source.w;
  1078. return this;
  1079. };
  1080. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1081. this.x = x;
  1082. this.y = y;
  1083. this.z = z;
  1084. this.w = w;
  1085. return this;
  1086. };
  1087. // Statics
  1088. Vector4.FromArray = function (array, offset) {
  1089. if (!offset) {
  1090. offset = 0;
  1091. }
  1092. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1093. };
  1094. Vector4.FromArrayToRef = function (array, offset, result) {
  1095. result.x = array[offset];
  1096. result.y = array[offset + 1];
  1097. result.z = array[offset + 2];
  1098. result.w = array[offset + 3];
  1099. };
  1100. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1101. result.x = array[offset];
  1102. result.y = array[offset + 1];
  1103. result.z = array[offset + 2];
  1104. result.w = array[offset + 3];
  1105. };
  1106. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1107. result.x = x;
  1108. result.y = y;
  1109. result.z = z;
  1110. result.w = w;
  1111. };
  1112. Vector4.Zero = function () {
  1113. return new Vector4(0, 0, 0, 0);
  1114. };
  1115. Vector4.Normalize = function (vector) {
  1116. var result = Vector4.Zero();
  1117. Vector4.NormalizeToRef(vector, result);
  1118. return result;
  1119. };
  1120. Vector4.NormalizeToRef = function (vector, result) {
  1121. result.copyFrom(vector);
  1122. result.normalize();
  1123. };
  1124. Vector4.Minimize = function (left, right) {
  1125. var min = left.clone();
  1126. min.MinimizeInPlace(right);
  1127. return min;
  1128. };
  1129. Vector4.Maximize = function (left, right) {
  1130. var max = left.clone();
  1131. max.MaximizeInPlace(right);
  1132. return max;
  1133. };
  1134. Vector4.Distance = function (value1, value2) {
  1135. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1136. };
  1137. Vector4.DistanceSquared = function (value1, value2) {
  1138. var x = value1.x - value2.x;
  1139. var y = value1.y - value2.y;
  1140. var z = value1.z - value2.z;
  1141. var w = value1.w - value2.w;
  1142. return (x * x) + (y * y) + (z * z) + (w * w);
  1143. };
  1144. Vector4.Center = function (value1, value2) {
  1145. var center = value1.add(value2);
  1146. center.scaleInPlace(0.5);
  1147. return center;
  1148. };
  1149. return Vector4;
  1150. })();
  1151. BABYLON.Vector4 = Vector4;
  1152. var Quaternion = (function () {
  1153. function Quaternion(x, y, z, w) {
  1154. if (x === void 0) { x = 0; }
  1155. if (y === void 0) { y = 0; }
  1156. if (z === void 0) { z = 0; }
  1157. if (w === void 0) { w = 1; }
  1158. this.x = x;
  1159. this.y = y;
  1160. this.z = z;
  1161. this.w = w;
  1162. }
  1163. Quaternion.prototype.toString = function () {
  1164. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1165. };
  1166. Quaternion.prototype.asArray = function () {
  1167. return [this.x, this.y, this.z, this.w];
  1168. };
  1169. Quaternion.prototype.equals = function (otherQuaternion) {
  1170. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1171. };
  1172. Quaternion.prototype.clone = function () {
  1173. return new Quaternion(this.x, this.y, this.z, this.w);
  1174. };
  1175. Quaternion.prototype.copyFrom = function (other) {
  1176. this.x = other.x;
  1177. this.y = other.y;
  1178. this.z = other.z;
  1179. this.w = other.w;
  1180. return this;
  1181. };
  1182. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1183. this.x = x;
  1184. this.y = y;
  1185. this.z = z;
  1186. this.w = w;
  1187. return this;
  1188. };
  1189. Quaternion.prototype.add = function (other) {
  1190. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1191. };
  1192. Quaternion.prototype.subtract = function (other) {
  1193. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1194. };
  1195. Quaternion.prototype.scale = function (value) {
  1196. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1197. };
  1198. Quaternion.prototype.multiply = function (q1) {
  1199. var result = new Quaternion(0, 0, 0, 1.0);
  1200. this.multiplyToRef(q1, result);
  1201. return result;
  1202. };
  1203. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1204. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1205. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1206. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1207. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1208. return this;
  1209. };
  1210. Quaternion.prototype.length = function () {
  1211. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1212. };
  1213. Quaternion.prototype.normalize = function () {
  1214. var length = 1.0 / this.length();
  1215. this.x *= length;
  1216. this.y *= length;
  1217. this.z *= length;
  1218. this.w *= length;
  1219. return this;
  1220. };
  1221. Quaternion.prototype.toEulerAngles = function () {
  1222. var result = Vector3.Zero();
  1223. this.toEulerAnglesToRef(result);
  1224. return result;
  1225. };
  1226. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1227. //result is an EulerAngles in the in the z-x-z convention
  1228. var qx = this.x;
  1229. var qy = this.y;
  1230. var qz = this.z;
  1231. var qw = this.w;
  1232. var qxy = qx * qy;
  1233. var qxz = qx * qz;
  1234. var qwy = qw * qy;
  1235. var qwz = qw * qz;
  1236. var qwx = qw * qx;
  1237. var qyz = qy * qz;
  1238. var sqx = qx * qx;
  1239. var sqy = qy * qy;
  1240. var determinant = sqx + sqy;
  1241. if (determinant !== 0.000 && determinant !== 1.000) {
  1242. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1243. result.y = Math.acos(1 - 2 * determinant);
  1244. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1245. }
  1246. else {
  1247. if (determinant === 0.0) {
  1248. result.x = 0.0;
  1249. result.y = 0.0;
  1250. 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)
  1251. }
  1252. else {
  1253. 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)
  1254. result.y = Math.PI;
  1255. result.z = 0.0;
  1256. }
  1257. }
  1258. return this;
  1259. };
  1260. Quaternion.prototype.toRotationMatrix = function (result) {
  1261. var xx = this.x * this.x;
  1262. var yy = this.y * this.y;
  1263. var zz = this.z * this.z;
  1264. var xy = this.x * this.y;
  1265. var zw = this.z * this.w;
  1266. var zx = this.z * this.x;
  1267. var yw = this.y * this.w;
  1268. var yz = this.y * this.z;
  1269. var xw = this.x * this.w;
  1270. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1271. result.m[1] = 2.0 * (xy + zw);
  1272. result.m[2] = 2.0 * (zx - yw);
  1273. result.m[3] = 0;
  1274. result.m[4] = 2.0 * (xy - zw);
  1275. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1276. result.m[6] = 2.0 * (yz + xw);
  1277. result.m[7] = 0;
  1278. result.m[8] = 2.0 * (zx + yw);
  1279. result.m[9] = 2.0 * (yz - xw);
  1280. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1281. result.m[11] = 0;
  1282. result.m[12] = 0;
  1283. result.m[13] = 0;
  1284. result.m[14] = 0;
  1285. result.m[15] = 1.0;
  1286. return this;
  1287. };
  1288. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1289. Quaternion.FromRotationMatrixToRef(matrix, this);
  1290. return this;
  1291. };
  1292. // Statics
  1293. Quaternion.FromRotationMatrix = function (matrix) {
  1294. var result = new Quaternion();
  1295. Quaternion.FromRotationMatrixToRef(matrix, result);
  1296. return result;
  1297. };
  1298. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1299. var data = matrix.m;
  1300. var m11 = data[0], m12 = data[4], m13 = data[8];
  1301. var m21 = data[1], m22 = data[5], m23 = data[9];
  1302. var m31 = data[2], m32 = data[6], m33 = data[10];
  1303. var trace = m11 + m22 + m33;
  1304. var s;
  1305. if (trace > 0) {
  1306. s = 0.5 / Math.sqrt(trace + 1.0);
  1307. result.w = 0.25 / s;
  1308. result.x = (m32 - m23) * s;
  1309. result.y = (m13 - m31) * s;
  1310. result.z = (m21 - m12) * s;
  1311. }
  1312. else if (m11 > m22 && m11 > m33) {
  1313. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1314. result.w = (m32 - m23) / s;
  1315. result.x = 0.25 * s;
  1316. result.y = (m12 + m21) / s;
  1317. result.z = (m13 + m31) / s;
  1318. }
  1319. else if (m22 > m33) {
  1320. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1321. result.w = (m13 - m31) / s;
  1322. result.x = (m12 + m21) / s;
  1323. result.y = 0.25 * s;
  1324. result.z = (m23 + m32) / s;
  1325. }
  1326. else {
  1327. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1328. result.w = (m21 - m12) / s;
  1329. result.x = (m13 + m31) / s;
  1330. result.y = (m23 + m32) / s;
  1331. result.z = 0.25 * s;
  1332. }
  1333. };
  1334. Quaternion.Inverse = function (q) {
  1335. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1336. };
  1337. Quaternion.Identity = function () {
  1338. return new Quaternion(0, 0, 0, 1);
  1339. };
  1340. Quaternion.RotationAxis = function (axis, angle) {
  1341. var result = new Quaternion();
  1342. var sin = Math.sin(angle / 2);
  1343. result.w = Math.cos(angle / 2);
  1344. result.x = axis.x * sin;
  1345. result.y = axis.y * sin;
  1346. result.z = axis.z * sin;
  1347. return result;
  1348. };
  1349. Quaternion.FromArray = function (array, offset) {
  1350. if (!offset) {
  1351. offset = 0;
  1352. }
  1353. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1354. };
  1355. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1356. var result = new Quaternion();
  1357. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1358. return result;
  1359. };
  1360. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1361. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1362. var halfRoll = roll * 0.5;
  1363. var halfPitch = pitch * 0.5;
  1364. var halfYaw = yaw * 0.5;
  1365. var sinRoll = Math.sin(halfRoll);
  1366. var cosRoll = Math.cos(halfRoll);
  1367. var sinPitch = Math.sin(halfPitch);
  1368. var cosPitch = Math.cos(halfPitch);
  1369. var sinYaw = Math.sin(halfYaw);
  1370. var cosYaw = Math.cos(halfYaw);
  1371. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1372. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1373. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1374. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1375. };
  1376. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1377. var result = new Quaternion();
  1378. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1379. return result;
  1380. };
  1381. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1382. // Produces a quaternion from Euler angles in the z-x-z orientation
  1383. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1384. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1385. var halfBeta = beta * 0.5;
  1386. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1387. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1388. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1389. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1390. };
  1391. Quaternion.Slerp = function (left, right, amount) {
  1392. var num2;
  1393. var num3;
  1394. var num = amount;
  1395. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1396. var flag = false;
  1397. if (num4 < 0) {
  1398. flag = true;
  1399. num4 = -num4;
  1400. }
  1401. if (num4 > 0.999999) {
  1402. num3 = 1 - num;
  1403. num2 = flag ? -num : num;
  1404. }
  1405. else {
  1406. var num5 = Math.acos(num4);
  1407. var num6 = (1.0 / Math.sin(num5));
  1408. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1409. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1410. }
  1411. 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));
  1412. };
  1413. return Quaternion;
  1414. })();
  1415. BABYLON.Quaternion = Quaternion;
  1416. var Matrix = (function () {
  1417. function Matrix() {
  1418. this.m = new Float32Array(16);
  1419. }
  1420. // Properties
  1421. Matrix.prototype.isIdentity = function () {
  1422. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1423. return false;
  1424. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1425. return false;
  1426. return true;
  1427. };
  1428. Matrix.prototype.determinant = function () {
  1429. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1430. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1431. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1432. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1433. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1434. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1435. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  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 && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1710. };
  1711. Matrix.prototype.clone = function () {
  1712. 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]);
  1713. };
  1714. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1715. translation.x = this.m[12];
  1716. translation.y = this.m[13];
  1717. translation.z = this.m[14];
  1718. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1719. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1720. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1721. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1722. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1723. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1724. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1725. rotation.x = 0;
  1726. rotation.y = 0;
  1727. rotation.z = 0;
  1728. rotation.w = 1;
  1729. return false;
  1730. }
  1731. 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);
  1732. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1733. return true;
  1734. };
  1735. // Statics
  1736. Matrix.FromArray = function (array, offset) {
  1737. var result = new Matrix();
  1738. if (!offset) {
  1739. offset = 0;
  1740. }
  1741. Matrix.FromArrayToRef(array, offset, result);
  1742. return result;
  1743. };
  1744. Matrix.FromArrayToRef = function (array, offset, result) {
  1745. for (var index = 0; index < 16; index++) {
  1746. result.m[index] = array[index + offset];
  1747. }
  1748. };
  1749. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1750. result.m[0] = initialM11;
  1751. result.m[1] = initialM12;
  1752. result.m[2] = initialM13;
  1753. result.m[3] = initialM14;
  1754. result.m[4] = initialM21;
  1755. result.m[5] = initialM22;
  1756. result.m[6] = initialM23;
  1757. result.m[7] = initialM24;
  1758. result.m[8] = initialM31;
  1759. result.m[9] = initialM32;
  1760. result.m[10] = initialM33;
  1761. result.m[11] = initialM34;
  1762. result.m[12] = initialM41;
  1763. result.m[13] = initialM42;
  1764. result.m[14] = initialM43;
  1765. result.m[15] = initialM44;
  1766. };
  1767. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1768. var result = new Matrix();
  1769. result.m[0] = initialM11;
  1770. result.m[1] = initialM12;
  1771. result.m[2] = initialM13;
  1772. result.m[3] = initialM14;
  1773. result.m[4] = initialM21;
  1774. result.m[5] = initialM22;
  1775. result.m[6] = initialM23;
  1776. result.m[7] = initialM24;
  1777. result.m[8] = initialM31;
  1778. result.m[9] = initialM32;
  1779. result.m[10] = initialM33;
  1780. result.m[11] = initialM34;
  1781. result.m[12] = initialM41;
  1782. result.m[13] = initialM42;
  1783. result.m[14] = initialM43;
  1784. result.m[15] = initialM44;
  1785. return result;
  1786. };
  1787. Matrix.Compose = function (scale, rotation, translation) {
  1788. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1789. var rotationMatrix = Matrix.Identity();
  1790. rotation.toRotationMatrix(rotationMatrix);
  1791. result = result.multiply(rotationMatrix);
  1792. result.setTranslation(translation);
  1793. return result;
  1794. };
  1795. Matrix.Identity = function () {
  1796. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1797. };
  1798. Matrix.IdentityToRef = function (result) {
  1799. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1800. };
  1801. Matrix.Zero = function () {
  1802. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1803. };
  1804. Matrix.RotationX = function (angle) {
  1805. var result = new Matrix();
  1806. Matrix.RotationXToRef(angle, result);
  1807. return result;
  1808. };
  1809. Matrix.Invert = function (source) {
  1810. var result = new Matrix();
  1811. source.invertToRef(result);
  1812. return result;
  1813. };
  1814. Matrix.RotationXToRef = function (angle, result) {
  1815. var s = Math.sin(angle);
  1816. var c = Math.cos(angle);
  1817. result.m[0] = 1.0;
  1818. result.m[15] = 1.0;
  1819. result.m[5] = c;
  1820. result.m[10] = c;
  1821. result.m[9] = -s;
  1822. result.m[6] = s;
  1823. result.m[1] = 0;
  1824. result.m[2] = 0;
  1825. result.m[3] = 0;
  1826. result.m[4] = 0;
  1827. result.m[7] = 0;
  1828. result.m[8] = 0;
  1829. result.m[11] = 0;
  1830. result.m[12] = 0;
  1831. result.m[13] = 0;
  1832. result.m[14] = 0;
  1833. };
  1834. Matrix.RotationY = function (angle) {
  1835. var result = new Matrix();
  1836. Matrix.RotationYToRef(angle, result);
  1837. return result;
  1838. };
  1839. Matrix.RotationYToRef = function (angle, result) {
  1840. var s = Math.sin(angle);
  1841. var c = Math.cos(angle);
  1842. result.m[5] = 1.0;
  1843. result.m[15] = 1.0;
  1844. result.m[0] = c;
  1845. result.m[2] = -s;
  1846. result.m[8] = s;
  1847. result.m[10] = c;
  1848. result.m[1] = 0;
  1849. result.m[3] = 0;
  1850. result.m[4] = 0;
  1851. result.m[6] = 0;
  1852. result.m[7] = 0;
  1853. result.m[9] = 0;
  1854. result.m[11] = 0;
  1855. result.m[12] = 0;
  1856. result.m[13] = 0;
  1857. result.m[14] = 0;
  1858. };
  1859. Matrix.RotationZ = function (angle) {
  1860. var result = new Matrix();
  1861. Matrix.RotationZToRef(angle, result);
  1862. return result;
  1863. };
  1864. Matrix.RotationZToRef = function (angle, result) {
  1865. var s = Math.sin(angle);
  1866. var c = Math.cos(angle);
  1867. result.m[10] = 1.0;
  1868. result.m[15] = 1.0;
  1869. result.m[0] = c;
  1870. result.m[1] = s;
  1871. result.m[4] = -s;
  1872. result.m[5] = c;
  1873. result.m[2] = 0;
  1874. result.m[3] = 0;
  1875. result.m[6] = 0;
  1876. result.m[7] = 0;
  1877. result.m[8] = 0;
  1878. result.m[9] = 0;
  1879. result.m[11] = 0;
  1880. result.m[12] = 0;
  1881. result.m[13] = 0;
  1882. result.m[14] = 0;
  1883. };
  1884. Matrix.RotationAxis = function (axis, angle) {
  1885. var s = Math.sin(-angle);
  1886. var c = Math.cos(-angle);
  1887. var c1 = 1 - c;
  1888. axis.normalize();
  1889. var result = Matrix.Zero();
  1890. result.m[0] = (axis.x * axis.x) * c1 + c;
  1891. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1892. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1893. result.m[3] = 0.0;
  1894. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1895. result.m[5] = (axis.y * axis.y) * c1 + c;
  1896. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1897. result.m[7] = 0.0;
  1898. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1899. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1900. result.m[10] = (axis.z * axis.z) * c1 + c;
  1901. result.m[11] = 0.0;
  1902. result.m[15] = 1.0;
  1903. return result;
  1904. };
  1905. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1906. var result = new Matrix();
  1907. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1908. return result;
  1909. };
  1910. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1911. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1912. this._tempQuaternion.toRotationMatrix(result);
  1913. };
  1914. Matrix.Scaling = function (x, y, z) {
  1915. var result = Matrix.Zero();
  1916. Matrix.ScalingToRef(x, y, z, result);
  1917. return result;
  1918. };
  1919. Matrix.ScalingToRef = function (x, y, z, result) {
  1920. result.m[0] = x;
  1921. result.m[1] = 0;
  1922. result.m[2] = 0;
  1923. result.m[3] = 0;
  1924. result.m[4] = 0;
  1925. result.m[5] = y;
  1926. result.m[6] = 0;
  1927. result.m[7] = 0;
  1928. result.m[8] = 0;
  1929. result.m[9] = 0;
  1930. result.m[10] = z;
  1931. result.m[11] = 0;
  1932. result.m[12] = 0;
  1933. result.m[13] = 0;
  1934. result.m[14] = 0;
  1935. result.m[15] = 1.0;
  1936. };
  1937. Matrix.Translation = function (x, y, z) {
  1938. var result = Matrix.Identity();
  1939. Matrix.TranslationToRef(x, y, z, result);
  1940. return result;
  1941. };
  1942. Matrix.TranslationToRef = function (x, y, z, result) {
  1943. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1944. };
  1945. Matrix.LookAtLH = function (eye, target, up) {
  1946. var result = Matrix.Zero();
  1947. Matrix.LookAtLHToRef(eye, target, up, result);
  1948. return result;
  1949. };
  1950. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1951. // Z axis
  1952. target.subtractToRef(eye, this._zAxis);
  1953. this._zAxis.normalize();
  1954. // X axis
  1955. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1956. this._xAxis.normalize();
  1957. // Y axis
  1958. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1959. this._yAxis.normalize();
  1960. // Eye angles
  1961. var ex = -Vector3.Dot(this._xAxis, eye);
  1962. var ey = -Vector3.Dot(this._yAxis, eye);
  1963. var ez = -Vector3.Dot(this._zAxis, eye);
  1964. 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);
  1965. };
  1966. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1967. var out = result.m;
  1968. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1969. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1970. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1971. // cc.kmVec3Subtract(f, pCenter, pEye);
  1972. var f = SIMD.float32x4.sub(center, eye);
  1973. // cc.kmVec3Normalize(f, f);
  1974. var tmp = SIMD.float32x4.mul(f, f);
  1975. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1976. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1977. // cc.kmVec3Assign(up, pUp);
  1978. // cc.kmVec3Normalize(up, up);
  1979. tmp = SIMD.float32x4.mul(up, up);
  1980. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1981. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1982. // cc.kmVec3Cross(s, f, up);
  1983. 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)));
  1984. // cc.kmVec3Normalize(s, s);
  1985. tmp = SIMD.float32x4.mul(s, s);
  1986. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1987. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1988. // cc.kmVec3Cross(u, s, f);
  1989. 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)));
  1990. // cc.kmVec3Normalize(s, s);
  1991. tmp = SIMD.float32x4.mul(s, s);
  1992. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1993. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1994. var zero = SIMD.float32x4.splat(0.0);
  1995. s = SIMD.float32x4.neg(s);
  1996. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1997. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1998. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1999. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2000. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2001. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2002. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2003. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2004. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2005. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2006. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2007. var b3 = SIMD.float32x4.neg(eye);
  2008. b3 = SIMD.float32x4.withW(b3, 1.0);
  2009. 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)))));
  2010. 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)))));
  2011. 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)))));
  2012. 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)))));
  2013. };
  2014. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2015. var matrix = Matrix.Zero();
  2016. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2017. return matrix;
  2018. };
  2019. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2020. var hw = 2.0 / width;
  2021. var hh = 2.0 / height;
  2022. var id = 1.0 / (zfar - znear);
  2023. var nid = znear / (znear - zfar);
  2024. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2025. };
  2026. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2027. var matrix = Matrix.Zero();
  2028. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2029. return matrix;
  2030. };
  2031. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2032. result.m[0] = 2.0 / (right - left);
  2033. result.m[1] = result.m[2] = result.m[3] = 0;
  2034. result.m[5] = 2.0 / (top - bottom);
  2035. result.m[4] = result.m[6] = result.m[7] = 0;
  2036. result.m[10] = -1.0 / (znear - zfar);
  2037. result.m[8] = result.m[9] = result.m[11] = 0;
  2038. result.m[12] = (left + right) / (left - right);
  2039. result.m[13] = (top + bottom) / (bottom - top);
  2040. result.m[14] = znear / (znear - zfar);
  2041. result.m[15] = 1.0;
  2042. };
  2043. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2044. var matrix = Matrix.Zero();
  2045. matrix.m[0] = (2.0 * znear) / width;
  2046. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2047. matrix.m[5] = (2.0 * znear) / height;
  2048. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2049. matrix.m[10] = -zfar / (znear - zfar);
  2050. matrix.m[8] = matrix.m[9] = 0.0;
  2051. matrix.m[11] = 1.0;
  2052. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2053. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2054. return matrix;
  2055. };
  2056. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2057. var matrix = Matrix.Zero();
  2058. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2059. return matrix;
  2060. };
  2061. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2062. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2063. var tan = 1.0 / (Math.tan(fov * 0.5));
  2064. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2065. if (v_fixed) {
  2066. result.m[0] = tan / aspect;
  2067. }
  2068. else {
  2069. result.m[0] = tan;
  2070. }
  2071. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2072. if (v_fixed) {
  2073. result.m[5] = tan;
  2074. }
  2075. else {
  2076. result.m[5] = tan * aspect;
  2077. }
  2078. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2079. result.m[8] = result.m[9] = 0.0;
  2080. result.m[10] = -zfar / (znear - zfar);
  2081. result.m[11] = 1.0;
  2082. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2083. result.m[14] = (znear * zfar) / (znear - zfar);
  2084. };
  2085. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2086. var cw = viewport.width;
  2087. var ch = viewport.height;
  2088. var cx = viewport.x;
  2089. var cy = viewport.y;
  2090. 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);
  2091. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2092. };
  2093. Matrix.Transpose = function (matrix) {
  2094. var result = new Matrix();
  2095. result.m[0] = matrix.m[0];
  2096. result.m[1] = matrix.m[4];
  2097. result.m[2] = matrix.m[8];
  2098. result.m[3] = matrix.m[12];
  2099. result.m[4] = matrix.m[1];
  2100. result.m[5] = matrix.m[5];
  2101. result.m[6] = matrix.m[9];
  2102. result.m[7] = matrix.m[13];
  2103. result.m[8] = matrix.m[2];
  2104. result.m[9] = matrix.m[6];
  2105. result.m[10] = matrix.m[10];
  2106. result.m[11] = matrix.m[14];
  2107. result.m[12] = matrix.m[3];
  2108. result.m[13] = matrix.m[7];
  2109. result.m[14] = matrix.m[11];
  2110. result.m[15] = matrix.m[15];
  2111. return result;
  2112. };
  2113. Matrix.Reflection = function (plane) {
  2114. var matrix = new Matrix();
  2115. Matrix.ReflectionToRef(plane, matrix);
  2116. return matrix;
  2117. };
  2118. Matrix.ReflectionToRef = function (plane, result) {
  2119. plane.normalize();
  2120. var x = plane.normal.x;
  2121. var y = plane.normal.y;
  2122. var z = plane.normal.z;
  2123. var temp = -2 * x;
  2124. var temp2 = -2 * y;
  2125. var temp3 = -2 * z;
  2126. result.m[0] = (temp * x) + 1;
  2127. result.m[1] = temp2 * x;
  2128. result.m[2] = temp3 * x;
  2129. result.m[3] = 0.0;
  2130. result.m[4] = temp * y;
  2131. result.m[5] = (temp2 * y) + 1;
  2132. result.m[6] = temp3 * y;
  2133. result.m[7] = 0.0;
  2134. result.m[8] = temp * z;
  2135. result.m[9] = temp2 * z;
  2136. result.m[10] = (temp3 * z) + 1;
  2137. result.m[11] = 0.0;
  2138. result.m[12] = temp * plane.d;
  2139. result.m[13] = temp2 * plane.d;
  2140. result.m[14] = temp3 * plane.d;
  2141. result.m[15] = 1.0;
  2142. };
  2143. Matrix._tempQuaternion = new Quaternion();
  2144. Matrix._xAxis = Vector3.Zero();
  2145. Matrix._yAxis = Vector3.Zero();
  2146. Matrix._zAxis = Vector3.Zero();
  2147. return Matrix;
  2148. })();
  2149. BABYLON.Matrix = Matrix;
  2150. var Plane = (function () {
  2151. function Plane(a, b, c, d) {
  2152. this.normal = new Vector3(a, b, c);
  2153. this.d = d;
  2154. }
  2155. Plane.prototype.asArray = function () {
  2156. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2157. };
  2158. // Methods
  2159. Plane.prototype.clone = function () {
  2160. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2161. };
  2162. Plane.prototype.normalize = function () {
  2163. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2164. var magnitude = 0;
  2165. if (norm !== 0) {
  2166. magnitude = 1.0 / norm;
  2167. }
  2168. this.normal.x *= magnitude;
  2169. this.normal.y *= magnitude;
  2170. this.normal.z *= magnitude;
  2171. this.d *= magnitude;
  2172. return this;
  2173. };
  2174. Plane.prototype.transform = function (transformation) {
  2175. var transposedMatrix = Matrix.Transpose(transformation);
  2176. var x = this.normal.x;
  2177. var y = this.normal.y;
  2178. var z = this.normal.z;
  2179. var d = this.d;
  2180. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2181. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2182. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2183. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2184. return new Plane(normalX, normalY, normalZ, finalD);
  2185. };
  2186. Plane.prototype.dotCoordinate = function (point) {
  2187. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2188. };
  2189. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2190. var x1 = point2.x - point1.x;
  2191. var y1 = point2.y - point1.y;
  2192. var z1 = point2.z - point1.z;
  2193. var x2 = point3.x - point1.x;
  2194. var y2 = point3.y - point1.y;
  2195. var z2 = point3.z - point1.z;
  2196. var yz = (y1 * z2) - (z1 * y2);
  2197. var xz = (z1 * x2) - (x1 * z2);
  2198. var xy = (x1 * y2) - (y1 * x2);
  2199. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2200. var invPyth;
  2201. if (pyth !== 0) {
  2202. invPyth = 1.0 / pyth;
  2203. }
  2204. else {
  2205. invPyth = 0;
  2206. }
  2207. this.normal.x = yz * invPyth;
  2208. this.normal.y = xz * invPyth;
  2209. this.normal.z = xy * invPyth;
  2210. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2211. return this;
  2212. };
  2213. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2214. var dot = Vector3.Dot(this.normal, direction);
  2215. return (dot <= epsilon);
  2216. };
  2217. Plane.prototype.signedDistanceTo = function (point) {
  2218. return Vector3.Dot(point, this.normal) + this.d;
  2219. };
  2220. // Statics
  2221. Plane.FromArray = function (array) {
  2222. return new Plane(array[0], array[1], array[2], array[3]);
  2223. };
  2224. Plane.FromPoints = function (point1, point2, point3) {
  2225. var result = new Plane(0, 0, 0, 0);
  2226. result.copyFromPoints(point1, point2, point3);
  2227. return result;
  2228. };
  2229. Plane.FromPositionAndNormal = function (origin, normal) {
  2230. var result = new Plane(0, 0, 0, 0);
  2231. normal.normalize();
  2232. result.normal = normal;
  2233. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2234. return result;
  2235. };
  2236. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2237. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2238. return Vector3.Dot(point, normal) + d;
  2239. };
  2240. return Plane;
  2241. })();
  2242. BABYLON.Plane = Plane;
  2243. var Viewport = (function () {
  2244. function Viewport(x, y, width, height) {
  2245. this.x = x;
  2246. this.y = y;
  2247. this.width = width;
  2248. this.height = height;
  2249. }
  2250. Viewport.prototype.toGlobal = function (engine) {
  2251. var width = engine.getRenderWidth();
  2252. var height = engine.getRenderHeight();
  2253. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2254. };
  2255. return Viewport;
  2256. })();
  2257. BABYLON.Viewport = Viewport;
  2258. var Frustum = (function () {
  2259. function Frustum() {
  2260. }
  2261. Frustum.GetPlanes = function (transform) {
  2262. var frustumPlanes = [];
  2263. for (var index = 0; index < 6; index++) {
  2264. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2265. }
  2266. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2267. return frustumPlanes;
  2268. };
  2269. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2270. // Near
  2271. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2272. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2273. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2274. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2275. frustumPlanes[0].normalize();
  2276. // Far
  2277. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2278. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2279. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2280. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2281. frustumPlanes[1].normalize();
  2282. // Left
  2283. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2284. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2285. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2286. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2287. frustumPlanes[2].normalize();
  2288. // Right
  2289. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2290. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2291. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2292. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2293. frustumPlanes[3].normalize();
  2294. // Top
  2295. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2296. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2297. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2298. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2299. frustumPlanes[4].normalize();
  2300. // Bottom
  2301. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2302. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2303. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2304. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2305. frustumPlanes[5].normalize();
  2306. };
  2307. return Frustum;
  2308. })();
  2309. BABYLON.Frustum = Frustum;
  2310. var Ray = (function () {
  2311. function Ray(origin, direction, length) {
  2312. if (length === void 0) { length = Number.MAX_VALUE; }
  2313. this.origin = origin;
  2314. this.direction = direction;
  2315. this.length = length;
  2316. }
  2317. // Methods
  2318. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2319. var d = 0.0;
  2320. var maxValue = Number.MAX_VALUE;
  2321. if (Math.abs(this.direction.x) < 0.0000001) {
  2322. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2323. return false;
  2324. }
  2325. }
  2326. else {
  2327. var inv = 1.0 / this.direction.x;
  2328. var min = (minimum.x - this.origin.x) * inv;
  2329. var max = (maximum.x - this.origin.x) * inv;
  2330. if (max === -Infinity) {
  2331. max = Infinity;
  2332. }
  2333. if (min > max) {
  2334. var temp = min;
  2335. min = max;
  2336. max = temp;
  2337. }
  2338. d = Math.max(min, d);
  2339. maxValue = Math.min(max, maxValue);
  2340. if (d > maxValue) {
  2341. return false;
  2342. }
  2343. }
  2344. if (Math.abs(this.direction.y) < 0.0000001) {
  2345. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2346. return false;
  2347. }
  2348. }
  2349. else {
  2350. inv = 1.0 / this.direction.y;
  2351. min = (minimum.y - this.origin.y) * inv;
  2352. max = (maximum.y - this.origin.y) * inv;
  2353. if (max === -Infinity) {
  2354. max = Infinity;
  2355. }
  2356. if (min > max) {
  2357. temp = min;
  2358. min = max;
  2359. max = temp;
  2360. }
  2361. d = Math.max(min, d);
  2362. maxValue = Math.min(max, maxValue);
  2363. if (d > maxValue) {
  2364. return false;
  2365. }
  2366. }
  2367. if (Math.abs(this.direction.z) < 0.0000001) {
  2368. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2369. return false;
  2370. }
  2371. }
  2372. else {
  2373. inv = 1.0 / this.direction.z;
  2374. min = (minimum.z - this.origin.z) * inv;
  2375. max = (maximum.z - this.origin.z) * inv;
  2376. if (max === -Infinity) {
  2377. max = Infinity;
  2378. }
  2379. if (min > max) {
  2380. temp = min;
  2381. min = max;
  2382. max = temp;
  2383. }
  2384. d = Math.max(min, d);
  2385. maxValue = Math.min(max, maxValue);
  2386. if (d > maxValue) {
  2387. return false;
  2388. }
  2389. }
  2390. return true;
  2391. };
  2392. Ray.prototype.intersectsBox = function (box) {
  2393. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2394. };
  2395. Ray.prototype.intersectsSphere = function (sphere) {
  2396. var x = sphere.center.x - this.origin.x;
  2397. var y = sphere.center.y - this.origin.y;
  2398. var z = sphere.center.z - this.origin.z;
  2399. var pyth = (x * x) + (y * y) + (z * z);
  2400. var rr = sphere.radius * sphere.radius;
  2401. if (pyth <= rr) {
  2402. return true;
  2403. }
  2404. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2405. if (dot < 0.0) {
  2406. return false;
  2407. }
  2408. var temp = pyth - (dot * dot);
  2409. return temp <= rr;
  2410. };
  2411. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2412. if (!this._edge1) {
  2413. this._edge1 = Vector3.Zero();
  2414. this._edge2 = Vector3.Zero();
  2415. this._pvec = Vector3.Zero();
  2416. this._tvec = Vector3.Zero();
  2417. this._qvec = Vector3.Zero();
  2418. }
  2419. vertex1.subtractToRef(vertex0, this._edge1);
  2420. vertex2.subtractToRef(vertex0, this._edge2);
  2421. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2422. var det = Vector3.Dot(this._edge1, this._pvec);
  2423. if (det === 0) {
  2424. return null;
  2425. }
  2426. var invdet = 1 / det;
  2427. this.origin.subtractToRef(vertex0, this._tvec);
  2428. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2429. if (bu < 0 || bu > 1.0) {
  2430. return null;
  2431. }
  2432. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2433. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2434. if (bv < 0 || bu + bv > 1.0) {
  2435. return null;
  2436. }
  2437. //check if the distance is longer than the predefined length.
  2438. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2439. if (distance > this.length) {
  2440. return null;
  2441. }
  2442. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2443. };
  2444. // Statics
  2445. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2446. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2447. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2448. var direction = end.subtract(start);
  2449. direction.normalize();
  2450. return new Ray(start, direction);
  2451. };
  2452. /**
  2453. * 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
  2454. * transformed to the given world matrix.
  2455. * @param origin The origin point
  2456. * @param end The end point
  2457. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2458. */
  2459. Ray.CreateNewFromTo = function (origin, end, world) {
  2460. if (world === void 0) { world = Matrix.Identity(); }
  2461. var direction = end.subtract(origin);
  2462. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2463. direction.normalize();
  2464. return Ray.Transform(new Ray(origin, direction, length), world);
  2465. };
  2466. Ray.Transform = function (ray, matrix) {
  2467. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2468. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2469. return new Ray(newOrigin, newDirection, ray.length);
  2470. };
  2471. return Ray;
  2472. })();
  2473. BABYLON.Ray = Ray;
  2474. (function (Space) {
  2475. Space[Space["LOCAL"] = 0] = "LOCAL";
  2476. Space[Space["WORLD"] = 1] = "WORLD";
  2477. })(BABYLON.Space || (BABYLON.Space = {}));
  2478. var Space = BABYLON.Space;
  2479. var Axis = (function () {
  2480. function Axis() {
  2481. }
  2482. Axis.X = new Vector3(1, 0, 0);
  2483. Axis.Y = new Vector3(0, 1, 0);
  2484. Axis.Z = new Vector3(0, 0, 1);
  2485. return Axis;
  2486. })();
  2487. BABYLON.Axis = Axis;
  2488. ;
  2489. var BezierCurve = (function () {
  2490. function BezierCurve() {
  2491. }
  2492. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2493. // Extract X (which is equal to time here)
  2494. var f0 = 1 - 3 * x2 + 3 * x1;
  2495. var f1 = 3 * x2 - 6 * x1;
  2496. var f2 = 3 * x1;
  2497. var refinedT = t;
  2498. for (var i = 0; i < 5; i++) {
  2499. var refinedT2 = refinedT * refinedT;
  2500. var refinedT3 = refinedT2 * refinedT;
  2501. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2502. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2503. refinedT -= (x - t) * slope;
  2504. refinedT = Math.min(1, Math.max(0, refinedT));
  2505. }
  2506. // Resolve cubic bezier for the given x
  2507. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2508. };
  2509. return BezierCurve;
  2510. })();
  2511. BABYLON.BezierCurve = BezierCurve;
  2512. (function (Orientation) {
  2513. Orientation[Orientation["CW"] = 0] = "CW";
  2514. Orientation[Orientation["CCW"] = 1] = "CCW";
  2515. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2516. var Orientation = BABYLON.Orientation;
  2517. var Angle = (function () {
  2518. function Angle(radians) {
  2519. var _this = this;
  2520. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2521. this.radians = function () { return _this._radians; };
  2522. this._radians = radians;
  2523. if (this._radians < 0)
  2524. this._radians += (2 * Math.PI);
  2525. }
  2526. Angle.BetweenTwoPoints = function (a, b) {
  2527. var delta = b.subtract(a);
  2528. var theta = Math.atan2(delta.y, delta.x);
  2529. return new Angle(theta);
  2530. };
  2531. Angle.FromRadians = function (radians) {
  2532. return new Angle(radians);
  2533. };
  2534. Angle.FromDegrees = function (degrees) {
  2535. return new Angle(degrees * Math.PI / 180);
  2536. };
  2537. return Angle;
  2538. })();
  2539. BABYLON.Angle = Angle;
  2540. var Arc2 = (function () {
  2541. function Arc2(startPoint, midPoint, endPoint) {
  2542. this.startPoint = startPoint;
  2543. this.midPoint = midPoint;
  2544. this.endPoint = endPoint;
  2545. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2546. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2547. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2548. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2549. 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);
  2550. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2551. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2552. var a1 = this.startAngle.degrees();
  2553. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2554. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2555. // angles correction
  2556. if (a2 - a1 > +180.0)
  2557. a2 -= 360.0;
  2558. if (a2 - a1 < -180.0)
  2559. a2 += 360.0;
  2560. if (a3 - a2 > +180.0)
  2561. a3 -= 360.0;
  2562. if (a3 - a2 < -180.0)
  2563. a3 += 360.0;
  2564. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2565. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2566. }
  2567. return Arc2;
  2568. })();
  2569. BABYLON.Arc2 = Arc2;
  2570. var PathCursor = (function () {
  2571. function PathCursor(path) {
  2572. this.path = path;
  2573. this._onchange = new Array();
  2574. this.value = 0;
  2575. this.animations = new Array();
  2576. }
  2577. PathCursor.prototype.getPoint = function () {
  2578. var point = this.path.getPointAtLengthPosition(this.value);
  2579. return new Vector3(point.x, 0, point.y);
  2580. };
  2581. PathCursor.prototype.moveAhead = function (step) {
  2582. if (step === void 0) { step = 0.002; }
  2583. this.move(step);
  2584. return this;
  2585. };
  2586. PathCursor.prototype.moveBack = function (step) {
  2587. if (step === void 0) { step = 0.002; }
  2588. this.move(-step);
  2589. return this;
  2590. };
  2591. PathCursor.prototype.move = function (step) {
  2592. if (Math.abs(step) > 1) {
  2593. throw "step size should be less than 1.";
  2594. }
  2595. this.value += step;
  2596. this.ensureLimits();
  2597. this.raiseOnChange();
  2598. return this;
  2599. };
  2600. PathCursor.prototype.ensureLimits = function () {
  2601. while (this.value > 1) {
  2602. this.value -= 1;
  2603. }
  2604. while (this.value < 0) {
  2605. this.value += 1;
  2606. }
  2607. return this;
  2608. };
  2609. // used by animation engine
  2610. PathCursor.prototype.markAsDirty = function (propertyName) {
  2611. this.ensureLimits();
  2612. this.raiseOnChange();
  2613. return this;
  2614. };
  2615. PathCursor.prototype.raiseOnChange = function () {
  2616. var _this = this;
  2617. this._onchange.forEach(function (f) { return f(_this); });
  2618. return this;
  2619. };
  2620. PathCursor.prototype.onchange = function (f) {
  2621. this._onchange.push(f);
  2622. return this;
  2623. };
  2624. return PathCursor;
  2625. })();
  2626. BABYLON.PathCursor = PathCursor;
  2627. var Path2 = (function () {
  2628. function Path2(x, y) {
  2629. this._points = new Array();
  2630. this._length = 0;
  2631. this.closed = false;
  2632. this._points.push(new Vector2(x, y));
  2633. }
  2634. Path2.prototype.addLineTo = function (x, y) {
  2635. if (closed) {
  2636. BABYLON.Tools.Error("cannot add lines to closed paths");
  2637. return this;
  2638. }
  2639. var newPoint = new Vector2(x, y);
  2640. var previousPoint = this._points[this._points.length - 1];
  2641. this._points.push(newPoint);
  2642. this._length += newPoint.subtract(previousPoint).length();
  2643. return this;
  2644. };
  2645. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2646. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2647. if (closed) {
  2648. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2649. return this;
  2650. }
  2651. var startPoint = this._points[this._points.length - 1];
  2652. var midPoint = new Vector2(midX, midY);
  2653. var endPoint = new Vector2(endX, endY);
  2654. var arc = new Arc2(startPoint, midPoint, endPoint);
  2655. var increment = arc.angle.radians() / numberOfSegments;
  2656. if (arc.orientation === 0 /* CW */)
  2657. increment *= -1;
  2658. var currentAngle = arc.startAngle.radians() + increment;
  2659. for (var i = 0; i < numberOfSegments; i++) {
  2660. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2661. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2662. this.addLineTo(x, y);
  2663. currentAngle += increment;
  2664. }
  2665. return this;
  2666. };
  2667. Path2.prototype.close = function () {
  2668. this.closed = true;
  2669. return this;
  2670. };
  2671. Path2.prototype.length = function () {
  2672. var result = this._length;
  2673. if (!this.closed) {
  2674. var lastPoint = this._points[this._points.length - 1];
  2675. var firstPoint = this._points[0];
  2676. result += (firstPoint.subtract(lastPoint).length());
  2677. }
  2678. return result;
  2679. };
  2680. Path2.prototype.getPoints = function () {
  2681. return this._points;
  2682. };
  2683. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2684. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2685. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2686. return Vector2.Zero();
  2687. }
  2688. var lengthPosition = normalizedLengthPosition * this.length();
  2689. var previousOffset = 0;
  2690. for (var i = 0; i < this._points.length; i++) {
  2691. var j = (i + 1) % this._points.length;
  2692. var a = this._points[i];
  2693. var b = this._points[j];
  2694. var bToA = b.subtract(a);
  2695. var nextOffset = (bToA.length() + previousOffset);
  2696. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2697. var dir = bToA.normalize();
  2698. var localOffset = lengthPosition - previousOffset;
  2699. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2700. }
  2701. previousOffset = nextOffset;
  2702. }
  2703. BABYLON.Tools.Error("internal error");
  2704. return Vector2.Zero();
  2705. };
  2706. Path2.StartingAt = function (x, y) {
  2707. return new Path2(x, y);
  2708. };
  2709. return Path2;
  2710. })();
  2711. BABYLON.Path2 = Path2;
  2712. var Path3D = (function () {
  2713. function Path3D(path, firstNormal) {
  2714. this.path = path;
  2715. this._curve = new Array();
  2716. this._distances = new Array();
  2717. this._tangents = new Array();
  2718. this._normals = new Array();
  2719. this._binormals = new Array();
  2720. for (var p = 0; p < path.length; p++) {
  2721. this._curve[p] = path[p].clone(); // hard copy
  2722. }
  2723. this._compute(firstNormal);
  2724. }
  2725. Path3D.prototype.getCurve = function () {
  2726. return this._curve;
  2727. };
  2728. Path3D.prototype.getTangents = function () {
  2729. return this._tangents;
  2730. };
  2731. Path3D.prototype.getNormals = function () {
  2732. return this._normals;
  2733. };
  2734. Path3D.prototype.getBinormals = function () {
  2735. return this._binormals;
  2736. };
  2737. Path3D.prototype.getDistances = function () {
  2738. return this._distances;
  2739. };
  2740. Path3D.prototype.update = function (path, firstNormal) {
  2741. for (var p = 0; p < path.length; p++) {
  2742. this._curve[p].x = path[p].x;
  2743. this._curve[p].y = path[p].y;
  2744. this._curve[p].z = path[p].z;
  2745. }
  2746. this._compute(firstNormal);
  2747. return this;
  2748. };
  2749. // private function compute() : computes tangents, normals and binormals
  2750. Path3D.prototype._compute = function (firstNormal) {
  2751. var l = this._curve.length;
  2752. // first and last tangents
  2753. this._tangents[0] = this._getFirstNonNullVector(0);
  2754. this._tangents[0].normalize();
  2755. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2756. this._tangents[l - 1].normalize();
  2757. // normals and binormals at first point : arbitrary vector with _normalVector()
  2758. var tg0 = this._tangents[0];
  2759. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2760. this._normals[0] = pp0;
  2761. this._normals[0].normalize();
  2762. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2763. this._binormals[0].normalize();
  2764. this._distances[0] = 0;
  2765. // normals and binormals : next points
  2766. var prev; // previous vector (segment)
  2767. var cur; // current vector (segment)
  2768. var curTang; // current tangent
  2769. var prevNorm; // previous normal
  2770. var prevBinor; // previous binormal
  2771. for (var i = 1; i < l; i++) {
  2772. // tangents
  2773. prev = this._getLastNonNullVector(i);
  2774. if (i < l - 1) {
  2775. cur = this._getFirstNonNullVector(i);
  2776. this._tangents[i] = prev.add(cur);
  2777. this._tangents[i].normalize();
  2778. }
  2779. this._distances[i] = this._distances[i - 1] + prev.length();
  2780. // normals and binormals
  2781. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2782. curTang = this._tangents[i];
  2783. prevNorm = this._normals[i - 1];
  2784. prevBinor = this._binormals[i - 1];
  2785. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2786. this._normals[i].normalize();
  2787. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2788. this._binormals[i].normalize();
  2789. }
  2790. };
  2791. // private function getFirstNonNullVector(index)
  2792. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2793. Path3D.prototype._getFirstNonNullVector = function (index) {
  2794. var i = 1;
  2795. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2796. while (nNVector.length() == 0 && index + i + 1 < this._curve.length) {
  2797. i++;
  2798. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2799. }
  2800. return nNVector;
  2801. };
  2802. // private function getLastNonNullVector(index)
  2803. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2804. Path3D.prototype._getLastNonNullVector = function (index) {
  2805. var i = 1;
  2806. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2807. while (nLVector.length() == 0 && index > i + 1) {
  2808. i++;
  2809. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2810. }
  2811. return nLVector;
  2812. };
  2813. // private function normalVector(v0, vt, va) :
  2814. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2815. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2816. Path3D.prototype._normalVector = function (v0, vt, va) {
  2817. var normal0;
  2818. if (va === undefined || va === null) {
  2819. var point;
  2820. if (vt.y !== 1) {
  2821. point = new Vector3(0, -1, 0);
  2822. }
  2823. else if (vt.x !== 1) {
  2824. point = new Vector3(1, 0, 0);
  2825. }
  2826. else if (vt.z !== 1) {
  2827. point = new Vector3(0, 0, 1);
  2828. }
  2829. normal0 = Vector3.Cross(vt, point);
  2830. }
  2831. else {
  2832. normal0 = Vector3.Cross(vt, va);
  2833. Vector3.CrossToRef(normal0, vt, normal0);
  2834. }
  2835. normal0.normalize();
  2836. return normal0;
  2837. };
  2838. return Path3D;
  2839. })();
  2840. BABYLON.Path3D = Path3D;
  2841. var Curve3 = (function () {
  2842. function Curve3(points) {
  2843. this._length = 0;
  2844. this._points = points;
  2845. this._length = this._computeLength(points);
  2846. }
  2847. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2848. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2849. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2850. var bez = new Array();
  2851. var equation = function (t, val0, val1, val2) {
  2852. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2853. return res;
  2854. };
  2855. for (var i = 0; i <= nbPoints; i++) {
  2856. 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)));
  2857. }
  2858. return new Curve3(bez);
  2859. };
  2860. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2861. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2862. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2863. var bez = new Array();
  2864. var equation = function (t, val0, val1, val2, val3) {
  2865. 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;
  2866. return res;
  2867. };
  2868. for (var i = 0; i <= nbPoints; i++) {
  2869. 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)));
  2870. }
  2871. return new Curve3(bez);
  2872. };
  2873. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2874. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2875. var hermite = new Array();
  2876. var step = 1 / nbPoints;
  2877. for (var i = 0; i <= nbPoints; i++) {
  2878. hermite.push(BABYLON.Vector3.Hermite(p1, t1, p2, t2, i * step));
  2879. }
  2880. return new Curve3(hermite);
  2881. };
  2882. Curve3.prototype.getPoints = function () {
  2883. return this._points;
  2884. };
  2885. Curve3.prototype.length = function () {
  2886. return this._length;
  2887. };
  2888. Curve3.prototype.continue = function (curve) {
  2889. var lastPoint = this._points[this._points.length - 1];
  2890. var continuedPoints = this._points.slice();
  2891. var curvePoints = curve.getPoints();
  2892. for (var i = 1; i < curvePoints.length; i++) {
  2893. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2894. }
  2895. var continuedCurve = new Curve3(continuedPoints);
  2896. return continuedCurve;
  2897. };
  2898. Curve3.prototype._computeLength = function (path) {
  2899. var l = 0;
  2900. for (var i = 1; i < path.length; i++) {
  2901. l += (path[i].subtract(path[i - 1])).length();
  2902. }
  2903. return l;
  2904. };
  2905. return Curve3;
  2906. })();
  2907. BABYLON.Curve3 = Curve3;
  2908. // Vertex formats
  2909. var PositionNormalVertex = (function () {
  2910. function PositionNormalVertex(position, normal) {
  2911. if (position === void 0) { position = Vector3.Zero(); }
  2912. if (normal === void 0) { normal = Vector3.Up(); }
  2913. this.position = position;
  2914. this.normal = normal;
  2915. }
  2916. PositionNormalVertex.prototype.clone = function () {
  2917. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2918. };
  2919. return PositionNormalVertex;
  2920. })();
  2921. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2922. var PositionNormalTextureVertex = (function () {
  2923. function PositionNormalTextureVertex(position, normal, uv) {
  2924. if (position === void 0) { position = Vector3.Zero(); }
  2925. if (normal === void 0) { normal = Vector3.Up(); }
  2926. if (uv === void 0) { uv = Vector2.Zero(); }
  2927. this.position = position;
  2928. this.normal = normal;
  2929. this.uv = uv;
  2930. }
  2931. PositionNormalTextureVertex.prototype.clone = function () {
  2932. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2933. };
  2934. return PositionNormalTextureVertex;
  2935. })();
  2936. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2937. // SIMD
  2938. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2939. var previousInvertToRef = Matrix.prototype.invertToRef;
  2940. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2941. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2942. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2943. var SIMDHelper = (function () {
  2944. function SIMDHelper() {
  2945. }
  2946. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2947. get: function () {
  2948. return SIMDHelper._isEnabled;
  2949. },
  2950. enumerable: true,
  2951. configurable: true
  2952. });
  2953. SIMDHelper.DisableSIMD = function () {
  2954. // Replace functions
  2955. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2956. Matrix.prototype.invertToRef = previousInvertToRef;
  2957. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2958. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2959. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2960. SIMDHelper._isEnabled = false;
  2961. };
  2962. SIMDHelper.EnableSIMD = function () {
  2963. if (window.SIMD === undefined) {
  2964. return;
  2965. }
  2966. // Replace functions
  2967. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2968. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2969. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2970. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2971. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2972. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2973. get: function () {
  2974. return this._data[0];
  2975. },
  2976. set: function (value) {
  2977. if (!this._data) {
  2978. this._data = new Float32Array(3);
  2979. }
  2980. this._data[0] = value;
  2981. }
  2982. });
  2983. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2984. get: function () {
  2985. return this._data[1];
  2986. },
  2987. set: function (value) {
  2988. this._data[1] = value;
  2989. }
  2990. });
  2991. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2992. get: function () {
  2993. return this._data[2];
  2994. },
  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. catch (ex) {
  3192. blobTextureURL = URL.createObjectURL(blob);
  3193. }
  3194. }
  3195. image.src = blobTextureURL;
  3196. };
  3197. if (Database.isUASupportingBlobStorage) {
  3198. var xhr = new XMLHttpRequest(), blob;
  3199. xhr.open("GET", url, true);
  3200. xhr.responseType = "blob";
  3201. xhr.addEventListener("load", function () {
  3202. if (xhr.status === 200) {
  3203. // Blob as response (XHR2)
  3204. blob = xhr.response;
  3205. var transaction = _this.db.transaction(["textures"], "readwrite");
  3206. // the transaction could abort because of a QuotaExceededError error
  3207. transaction.onabort = function (event) {
  3208. try {
  3209. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3210. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3211. this.hasReachedQuota = true;
  3212. }
  3213. }
  3214. catch (ex) {
  3215. }
  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. }
  3325. callback(-1);
  3326. };
  3327. transaction.oncomplete = function (event) {
  3328. callback(_this.manifestVersionFound);
  3329. };
  3330. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3331. // Put the scene into the database
  3332. var addRequest = transaction.objectStore("versions").put(newVersion);
  3333. addRequest.onsuccess = function (event) {
  3334. };
  3335. addRequest.onerror = function (event) {
  3336. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3337. };
  3338. }
  3339. catch (ex) {
  3340. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3341. callback(-1);
  3342. }
  3343. }
  3344. else {
  3345. callback(-1);
  3346. }
  3347. };
  3348. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3349. var _this = this;
  3350. var completeUrl = Database.ReturnFullUrlLocation(url);
  3351. var saveAndLoadFile = function (event) {
  3352. // the scene is not yet in the DB, let's try to save it
  3353. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3354. };
  3355. this._checkVersionFromDB(completeUrl, function (version) {
  3356. if (version !== -1) {
  3357. if (!_this.mustUpdateRessources) {
  3358. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3359. }
  3360. else {
  3361. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3362. }
  3363. }
  3364. else {
  3365. errorCallback();
  3366. }
  3367. });
  3368. };
  3369. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3370. if (this.isSupported) {
  3371. var targetStore;
  3372. if (url.indexOf(".babylon") !== -1) {
  3373. targetStore = "scenes";
  3374. }
  3375. else {
  3376. targetStore = "textures";
  3377. }
  3378. var file;
  3379. var transaction = this.db.transaction([targetStore]);
  3380. transaction.oncomplete = function (event) {
  3381. if (file) {
  3382. callback(file.data);
  3383. }
  3384. else {
  3385. notInDBCallback();
  3386. }
  3387. };
  3388. transaction.onabort = function (event) {
  3389. notInDBCallback();
  3390. };
  3391. var getRequest = transaction.objectStore(targetStore).get(url);
  3392. getRequest.onsuccess = function (event) {
  3393. file = (event.target).result;
  3394. };
  3395. getRequest.onerror = function (event) {
  3396. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3397. notInDBCallback();
  3398. };
  3399. }
  3400. else {
  3401. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3402. callback();
  3403. }
  3404. };
  3405. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3406. var _this = this;
  3407. if (this.isSupported) {
  3408. var targetStore;
  3409. if (url.indexOf(".babylon") !== -1) {
  3410. targetStore = "scenes";
  3411. }
  3412. else {
  3413. targetStore = "textures";
  3414. }
  3415. // Create XHR
  3416. var xhr = new XMLHttpRequest(), fileData;
  3417. xhr.open("GET", url, true);
  3418. if (useArrayBuffer) {
  3419. xhr.responseType = "arraybuffer";
  3420. }
  3421. xhr.onprogress = progressCallback;
  3422. xhr.addEventListener("load", function () {
  3423. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3424. // Blob as response (XHR2)
  3425. //fileData = xhr.responseText;
  3426. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3427. if (!_this.hasReachedQuota) {
  3428. // Open a transaction to the database
  3429. var transaction = _this.db.transaction([targetStore], "readwrite");
  3430. // the transaction could abort because of a QuotaExceededError error
  3431. transaction.onabort = function (event) {
  3432. try {
  3433. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3434. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3435. this.hasReachedQuota = true;
  3436. }
  3437. }
  3438. catch (ex) {
  3439. }
  3440. callback(fileData);
  3441. };
  3442. transaction.oncomplete = function (event) {
  3443. callback(fileData);
  3444. };
  3445. var newFile;
  3446. if (targetStore === "scenes") {
  3447. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3448. }
  3449. else {
  3450. newFile = { textureUrl: url, data: fileData };
  3451. }
  3452. try {
  3453. // Put the scene into the database
  3454. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3455. addRequest.onsuccess = function (event) {
  3456. };
  3457. addRequest.onerror = function (event) {
  3458. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3459. };
  3460. }
  3461. catch (ex) {
  3462. callback(fileData);
  3463. }
  3464. }
  3465. else {
  3466. callback(fileData);
  3467. }
  3468. }
  3469. else {
  3470. callback();
  3471. }
  3472. }, false);
  3473. xhr.addEventListener("error", function (event) {
  3474. BABYLON.Tools.Error("error on XHR request.");
  3475. callback();
  3476. }, false);
  3477. xhr.send();
  3478. }
  3479. else {
  3480. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3481. callback();
  3482. }
  3483. };
  3484. Database.isUASupportingBlobStorage = true;
  3485. Database.parseURL = function (url) {
  3486. var a = document.createElement('a');
  3487. a.href = url;
  3488. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3489. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3490. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3491. return absLocation;
  3492. };
  3493. Database.ReturnFullUrlLocation = function (url) {
  3494. if (url.indexOf("http:/") === -1) {
  3495. return (BABYLON.Database.parseURL(window.location.href) + url);
  3496. }
  3497. else {
  3498. return url;
  3499. }
  3500. };
  3501. return Database;
  3502. })();
  3503. BABYLON.Database = Database;
  3504. })(BABYLON || (BABYLON = {}));
  3505. //# sourceMappingURL=babylon.database.js.map
  3506. var BABYLON;
  3507. (function (BABYLON) {
  3508. var Internals;
  3509. (function (Internals) {
  3510. /*
  3511. * Based on jsTGALoader - Javascript loader for TGA file
  3512. * By Vincent Thibault
  3513. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3514. */
  3515. var TGATools = (function () {
  3516. function TGATools() {
  3517. }
  3518. TGATools.GetTGAHeader = function (data) {
  3519. var offset = 0;
  3520. var header = {
  3521. id_length: data[offset++],
  3522. colormap_type: data[offset++],
  3523. image_type: data[offset++],
  3524. colormap_index: data[offset++] | data[offset++] << 8,
  3525. colormap_length: data[offset++] | data[offset++] << 8,
  3526. colormap_size: data[offset++],
  3527. origin: [
  3528. data[offset++] | data[offset++] << 8,
  3529. data[offset++] | data[offset++] << 8
  3530. ],
  3531. width: data[offset++] | data[offset++] << 8,
  3532. height: data[offset++] | data[offset++] << 8,
  3533. pixel_size: data[offset++],
  3534. flags: data[offset++]
  3535. };
  3536. return header;
  3537. };
  3538. TGATools.UploadContent = function (gl, data) {
  3539. // Not enough data to contain header ?
  3540. if (data.length < 19) {
  3541. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3542. return;
  3543. }
  3544. // Read Header
  3545. var offset = 18;
  3546. var header = TGATools.GetTGAHeader(data);
  3547. // Assume it's a valid Targa file.
  3548. if (header.id_length + offset > data.length) {
  3549. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3550. return;
  3551. }
  3552. // Skip not needed data
  3553. offset += header.id_length;
  3554. var use_rle = false;
  3555. var use_pal = false;
  3556. var use_rgb = false;
  3557. var use_grey = false;
  3558. switch (header.image_type) {
  3559. case TGATools._TYPE_RLE_INDEXED:
  3560. use_rle = true;
  3561. case TGATools._TYPE_INDEXED:
  3562. use_pal = true;
  3563. break;
  3564. case TGATools._TYPE_RLE_RGB:
  3565. use_rle = true;
  3566. case TGATools._TYPE_RGB:
  3567. use_rgb = true;
  3568. break;
  3569. case TGATools._TYPE_RLE_GREY:
  3570. use_rle = true;
  3571. case TGATools._TYPE_GREY:
  3572. use_grey = true;
  3573. break;
  3574. }
  3575. var pixel_data;
  3576. var numAlphaBits = header.flags & 0xf;
  3577. var pixel_size = header.pixel_size >> 3;
  3578. var pixel_total = header.width * header.height * pixel_size;
  3579. // Read palettes
  3580. var palettes;
  3581. if (use_pal) {
  3582. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3583. }
  3584. // Read LRE
  3585. if (use_rle) {
  3586. pixel_data = new Uint8Array(pixel_total);
  3587. var c, count, i;
  3588. var localOffset = 0;
  3589. var pixels = new Uint8Array(pixel_size);
  3590. while (offset < pixel_total && localOffset < pixel_total) {
  3591. c = data[offset++];
  3592. count = (c & 0x7f) + 1;
  3593. // RLE pixels
  3594. if (c & 0x80) {
  3595. for (i = 0; i < pixel_size; ++i) {
  3596. pixels[i] = data[offset++];
  3597. }
  3598. for (i = 0; i < count; ++i) {
  3599. pixel_data.set(pixels, localOffset + i * pixel_size);
  3600. }
  3601. localOffset += pixel_size * count;
  3602. }
  3603. else {
  3604. count *= pixel_size;
  3605. for (i = 0; i < count; ++i) {
  3606. pixel_data[localOffset + i] = data[offset++];
  3607. }
  3608. localOffset += count;
  3609. }
  3610. }
  3611. }
  3612. else {
  3613. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3614. }
  3615. // Load to texture
  3616. var x_start, y_start, x_step, y_step, y_end, x_end;
  3617. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3618. default:
  3619. case TGATools._ORIGIN_UL:
  3620. x_start = 0;
  3621. x_step = 1;
  3622. x_end = header.width;
  3623. y_start = 0;
  3624. y_step = 1;
  3625. y_end = header.height;
  3626. break;
  3627. case TGATools._ORIGIN_BL:
  3628. x_start = 0;
  3629. x_step = 1;
  3630. x_end = header.width;
  3631. y_start = header.height - 1;
  3632. y_step = -1;
  3633. y_end = -1;
  3634. break;
  3635. case TGATools._ORIGIN_UR:
  3636. x_start = header.width - 1;
  3637. x_step = -1;
  3638. x_end = -1;
  3639. y_start = 0;
  3640. y_step = 1;
  3641. y_end = header.height;
  3642. break;
  3643. case TGATools._ORIGIN_BR:
  3644. x_start = header.width - 1;
  3645. x_step = -1;
  3646. x_end = -1;
  3647. y_start = header.height - 1;
  3648. y_step = -1;
  3649. y_end = -1;
  3650. break;
  3651. }
  3652. // Load the specify method
  3653. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3654. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3655. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3656. };
  3657. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3658. var image = pixel_data, colormap = palettes;
  3659. var width = header.width, height = header.height;
  3660. var color, i = 0, x, y;
  3661. var imageData = new Uint8Array(width * height * 4);
  3662. for (y = y_start; y !== y_end; y += y_step) {
  3663. for (x = x_start; x !== x_end; x += x_step, i++) {
  3664. color = image[i];
  3665. imageData[(x + width * y) * 4 + 3] = 255;
  3666. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3667. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3668. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3669. }
  3670. }
  3671. return imageData;
  3672. };
  3673. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3674. var image = pixel_data;
  3675. var width = header.width, height = header.height;
  3676. var color, i = 0, x, y;
  3677. var imageData = new Uint8Array(width * height * 4);
  3678. for (y = y_start; y !== y_end; y += y_step) {
  3679. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3680. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3681. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3682. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3683. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3684. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3685. }
  3686. }
  3687. return imageData;
  3688. };
  3689. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3690. var image = pixel_data;
  3691. var width = header.width, height = header.height;
  3692. var i = 0, x, y;
  3693. var imageData = new Uint8Array(width * height * 4);
  3694. for (y = y_start; y !== y_end; y += y_step) {
  3695. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3696. imageData[(x + width * y) * 4 + 3] = 255;
  3697. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3698. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3699. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3700. }
  3701. }
  3702. return imageData;
  3703. };
  3704. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3705. var image = pixel_data;
  3706. var width = header.width, height = header.height;
  3707. var i = 0, x, y;
  3708. var imageData = new Uint8Array(width * height * 4);
  3709. for (y = y_start; y !== y_end; y += y_step) {
  3710. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3711. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3712. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3713. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3714. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3715. }
  3716. }
  3717. return imageData;
  3718. };
  3719. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3720. var image = pixel_data;
  3721. var width = header.width, height = header.height;
  3722. var color, i = 0, x, y;
  3723. var imageData = new Uint8Array(width * height * 4);
  3724. for (y = y_start; y !== y_end; y += y_step) {
  3725. for (x = x_start; x !== x_end; x += x_step, i++) {
  3726. color = image[i];
  3727. imageData[(x + width * y) * 4 + 0] = color;
  3728. imageData[(x + width * y) * 4 + 1] = color;
  3729. imageData[(x + width * y) * 4 + 2] = color;
  3730. imageData[(x + width * y) * 4 + 3] = 255;
  3731. }
  3732. }
  3733. return imageData;
  3734. };
  3735. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3736. var image = pixel_data;
  3737. var width = header.width, height = header.height;
  3738. var i = 0, x, y;
  3739. var imageData = new Uint8Array(width * height * 4);
  3740. for (y = y_start; y !== y_end; y += y_step) {
  3741. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3742. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3743. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3744. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3745. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3746. }
  3747. }
  3748. return imageData;
  3749. };
  3750. TGATools._TYPE_NO_DATA = 0;
  3751. TGATools._TYPE_INDEXED = 1;
  3752. TGATools._TYPE_RGB = 2;
  3753. TGATools._TYPE_GREY = 3;
  3754. TGATools._TYPE_RLE_INDEXED = 9;
  3755. TGATools._TYPE_RLE_RGB = 10;
  3756. TGATools._TYPE_RLE_GREY = 11;
  3757. TGATools._ORIGIN_MASK = 0x30;
  3758. TGATools._ORIGIN_SHIFT = 0x04;
  3759. TGATools._ORIGIN_BL = 0x00;
  3760. TGATools._ORIGIN_BR = 0x01;
  3761. TGATools._ORIGIN_UL = 0x02;
  3762. TGATools._ORIGIN_UR = 0x03;
  3763. return TGATools;
  3764. })();
  3765. Internals.TGATools = TGATools;
  3766. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3767. })(BABYLON || (BABYLON = {}));
  3768. //# sourceMappingURL=babylon.tools.tga.js.map
  3769. var BABYLON;
  3770. (function (BABYLON) {
  3771. var Internals;
  3772. (function (Internals) {
  3773. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3774. // All values and structures referenced from:
  3775. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3776. var DDS_MAGIC = 0x20534444;
  3777. 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;
  3778. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3779. 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;
  3780. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3781. function FourCCToInt32(value) {
  3782. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  3783. }
  3784. function Int32ToFourCC(value) {
  3785. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3786. }
  3787. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3788. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3789. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3790. var headerLengthInt = 31; // The header length in 32 bit ints
  3791. // Offsets into the header array
  3792. var off_magic = 0;
  3793. var off_size = 1;
  3794. var off_flags = 2;
  3795. var off_height = 3;
  3796. var off_width = 4;
  3797. var off_mipmapCount = 7;
  3798. var off_pfFlags = 20;
  3799. var off_pfFourCC = 21;
  3800. var off_RGBbpp = 22;
  3801. var off_RMask = 23;
  3802. var off_GMask = 24;
  3803. var off_BMask = 25;
  3804. var off_AMask = 26;
  3805. var off_caps1 = 27;
  3806. var off_caps2 = 28;
  3807. ;
  3808. var DDSTools = (function () {
  3809. function DDSTools() {
  3810. }
  3811. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3812. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3813. var mipmapCount = 1;
  3814. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3815. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3816. }
  3817. return {
  3818. width: header[off_width],
  3819. height: header[off_height],
  3820. mipmapCount: mipmapCount,
  3821. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3822. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3823. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3824. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3825. };
  3826. };
  3827. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3828. var byteArray = new Uint8Array(dataLength);
  3829. var srcData = new Uint8Array(arrayBuffer);
  3830. var index = 0;
  3831. for (var y = height - 1; y >= 0; y--) {
  3832. for (var x = 0; x < width; x++) {
  3833. var srcPos = dataOffset + (x + y * width) * 4;
  3834. byteArray[index + 2] = srcData[srcPos];
  3835. byteArray[index + 1] = srcData[srcPos + 1];
  3836. byteArray[index] = srcData[srcPos + 2];
  3837. byteArray[index + 3] = srcData[srcPos + 3];
  3838. index += 4;
  3839. }
  3840. }
  3841. return byteArray;
  3842. };
  3843. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3844. var byteArray = new Uint8Array(dataLength);
  3845. var srcData = new Uint8Array(arrayBuffer);
  3846. var index = 0;
  3847. for (var y = height - 1; y >= 0; y--) {
  3848. for (var x = 0; x < width; x++) {
  3849. var srcPos = dataOffset + (x + y * width) * 3;
  3850. byteArray[index + 2] = srcData[srcPos];
  3851. byteArray[index + 1] = srcData[srcPos + 1];
  3852. byteArray[index] = srcData[srcPos + 2];
  3853. index += 3;
  3854. }
  3855. }
  3856. return byteArray;
  3857. };
  3858. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3859. var byteArray = new Uint8Array(dataLength);
  3860. var srcData = new Uint8Array(arrayBuffer);
  3861. var index = 0;
  3862. for (var y = height - 1; y >= 0; y--) {
  3863. for (var x = 0; x < width; x++) {
  3864. var srcPos = dataOffset + (x + y * width);
  3865. byteArray[index] = srcData[srcPos];
  3866. index++;
  3867. }
  3868. }
  3869. return byteArray;
  3870. };
  3871. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3872. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3873. if (header[off_magic] != DDS_MAGIC) {
  3874. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3875. return;
  3876. }
  3877. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3878. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3879. return;
  3880. }
  3881. if (info.isFourCC) {
  3882. fourCC = header[off_pfFourCC];
  3883. switch (fourCC) {
  3884. case FOURCC_DXT1:
  3885. blockBytes = 8;
  3886. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3887. break;
  3888. case FOURCC_DXT3:
  3889. blockBytes = 16;
  3890. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3891. break;
  3892. case FOURCC_DXT5:
  3893. blockBytes = 16;
  3894. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3895. break;
  3896. default:
  3897. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  3898. return;
  3899. }
  3900. }
  3901. mipmapCount = 1;
  3902. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  3903. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3904. }
  3905. var bpp = header[off_RGBbpp];
  3906. for (var face = 0; face < faces; face++) {
  3907. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  3908. width = header[off_width];
  3909. height = header[off_height];
  3910. dataOffset = header[off_size] + 4;
  3911. for (i = 0; i < mipmapCount; ++i) {
  3912. if (info.isRGB) {
  3913. if (bpp == 24) {
  3914. dataLength = width * height * 3;
  3915. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3916. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  3917. }
  3918. else {
  3919. dataLength = width * height * 4;
  3920. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3921. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  3922. }
  3923. }
  3924. else if (info.isLuminance) {
  3925. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  3926. var unpaddedRowSize = width;
  3927. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  3928. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  3929. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3930. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  3931. }
  3932. else {
  3933. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  3934. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  3935. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  3936. }
  3937. dataOffset += dataLength;
  3938. width *= 0.5;
  3939. height *= 0.5;
  3940. width = Math.max(1.0, width);
  3941. height = Math.max(1.0, height);
  3942. }
  3943. }
  3944. };
  3945. return DDSTools;
  3946. })();
  3947. Internals.DDSTools = DDSTools;
  3948. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3949. })(BABYLON || (BABYLON = {}));
  3950. //# sourceMappingURL=babylon.tools.dds.js.map
  3951. var BABYLON;
  3952. (function (BABYLON) {
  3953. var SmartArray = (function () {
  3954. function SmartArray(capacity) {
  3955. this.length = 0;
  3956. this._duplicateId = 0;
  3957. this.data = new Array(capacity);
  3958. this._id = SmartArray._GlobalId++;
  3959. }
  3960. SmartArray.prototype.push = function (value) {
  3961. this.data[this.length++] = value;
  3962. if (this.length > this.data.length) {
  3963. this.data.length *= 2;
  3964. }
  3965. if (!value.__smartArrayFlags) {
  3966. value.__smartArrayFlags = {};
  3967. }
  3968. value.__smartArrayFlags[this._id] = this._duplicateId;
  3969. };
  3970. SmartArray.prototype.pushNoDuplicate = function (value) {
  3971. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3972. return;
  3973. }
  3974. this.push(value);
  3975. };
  3976. SmartArray.prototype.sort = function (compareFn) {
  3977. this.data.sort(compareFn);
  3978. };
  3979. SmartArray.prototype.reset = function () {
  3980. this.length = 0;
  3981. this._duplicateId++;
  3982. };
  3983. SmartArray.prototype.concat = function (array) {
  3984. if (array.length === 0) {
  3985. return;
  3986. }
  3987. if (this.length + array.length > this.data.length) {
  3988. this.data.length = (this.length + array.length) * 2;
  3989. }
  3990. for (var index = 0; index < array.length; index++) {
  3991. this.data[this.length++] = (array.data || array)[index];
  3992. }
  3993. };
  3994. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  3995. if (array.length === 0) {
  3996. return;
  3997. }
  3998. if (this.length + array.length > this.data.length) {
  3999. this.data.length = (this.length + array.length) * 2;
  4000. }
  4001. for (var index = 0; index < array.length; index++) {
  4002. var item = (array.data || array)[index];
  4003. this.pushNoDuplicate(item);
  4004. }
  4005. };
  4006. SmartArray.prototype.indexOf = function (value) {
  4007. var position = this.data.indexOf(value);
  4008. if (position >= this.length) {
  4009. return -1;
  4010. }
  4011. return position;
  4012. };
  4013. // Statics
  4014. SmartArray._GlobalId = 0;
  4015. return SmartArray;
  4016. })();
  4017. BABYLON.SmartArray = SmartArray;
  4018. })(BABYLON || (BABYLON = {}));
  4019. //# sourceMappingURL=babylon.smartArray.js.map
  4020. var BABYLON;
  4021. (function (BABYLON) {
  4022. var SmartCollection = (function () {
  4023. function SmartCollection(capacity) {
  4024. if (capacity === void 0) { capacity = 10; }
  4025. this.count = 0;
  4026. this._initialCapacity = capacity;
  4027. this.items = {};
  4028. this._keys = new Array(this._initialCapacity);
  4029. }
  4030. SmartCollection.prototype.add = function (key, item) {
  4031. if (this.items[key] != undefined) {
  4032. return -1;
  4033. }
  4034. this.items[key] = item;
  4035. //literal keys are always strings, but we keep source type of key in _keys array
  4036. this._keys[this.count++] = key;
  4037. if (this.count > this._keys.length) {
  4038. this._keys.length *= 2;
  4039. }
  4040. return this.count;
  4041. };
  4042. SmartCollection.prototype.remove = function (key) {
  4043. if (this.items[key] == undefined) {
  4044. return -1;
  4045. }
  4046. return this.removeItemOfIndex(this.indexOf(key));
  4047. };
  4048. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4049. if (index < this.count && index > -1) {
  4050. delete this.items[this._keys[index]];
  4051. while (index < this.count) {
  4052. this._keys[index] = this._keys[index + 1];
  4053. index++;
  4054. }
  4055. }
  4056. else {
  4057. return -1;
  4058. }
  4059. return --this.count;
  4060. };
  4061. SmartCollection.prototype.indexOf = function (key) {
  4062. for (var i = 0; i !== this.count; i++) {
  4063. if (this._keys[i] === key) {
  4064. return i;
  4065. }
  4066. }
  4067. return -1;
  4068. };
  4069. SmartCollection.prototype.item = function (key) {
  4070. return this.items[key];
  4071. };
  4072. SmartCollection.prototype.getAllKeys = function () {
  4073. if (this.count > 0) {
  4074. var keys = new Array(this.count);
  4075. for (var i = 0; i < this.count; i++) {
  4076. keys[i] = this._keys[i];
  4077. }
  4078. return keys;
  4079. }
  4080. else {
  4081. return undefined;
  4082. }
  4083. };
  4084. SmartCollection.prototype.getKeyByIndex = function (index) {
  4085. if (index < this.count && index > -1) {
  4086. return this._keys[index];
  4087. }
  4088. else {
  4089. return undefined;
  4090. }
  4091. };
  4092. SmartCollection.prototype.getItemByIndex = function (index) {
  4093. if (index < this.count && index > -1) {
  4094. return this.items[this._keys[index]];
  4095. }
  4096. else {
  4097. return undefined;
  4098. }
  4099. };
  4100. SmartCollection.prototype.empty = function () {
  4101. if (this.count > 0) {
  4102. this.count = 0;
  4103. this.items = {};
  4104. this._keys = new Array(this._initialCapacity);
  4105. }
  4106. };
  4107. SmartCollection.prototype.forEach = function (block) {
  4108. var key;
  4109. for (key in this.items) {
  4110. if (this.items.hasOwnProperty(key)) {
  4111. block(this.items[key]);
  4112. }
  4113. }
  4114. };
  4115. return SmartCollection;
  4116. })();
  4117. BABYLON.SmartCollection = SmartCollection;
  4118. })(BABYLON || (BABYLON = {}));
  4119. //# sourceMappingURL=babylon.smartCollection.js.map
  4120. var BABYLON;
  4121. (function (BABYLON) {
  4122. // Screenshots
  4123. var screenshotCanvas;
  4124. var cloneValue = function (source, destinationObject) {
  4125. if (!source)
  4126. return null;
  4127. if (source instanceof BABYLON.Mesh) {
  4128. return null;
  4129. }
  4130. if (source instanceof BABYLON.SubMesh) {
  4131. return source.clone(destinationObject);
  4132. }
  4133. else if (source.clone) {
  4134. return source.clone();
  4135. }
  4136. return null;
  4137. };
  4138. var Tools = (function () {
  4139. function Tools() {
  4140. }
  4141. Tools.SetImmediate = function (action) {
  4142. if (window.setImmediate) {
  4143. window.setImmediate(action);
  4144. }
  4145. else {
  4146. setTimeout(action, 1);
  4147. }
  4148. };
  4149. Tools.GetFilename = function (path) {
  4150. var index = path.lastIndexOf("/");
  4151. if (index < 0)
  4152. return path;
  4153. return path.substring(index + 1);
  4154. };
  4155. Tools.GetDOMTextContent = function (element) {
  4156. var result = "";
  4157. var child = element.firstChild;
  4158. while (child) {
  4159. if (child.nodeType === 3) {
  4160. result += child.textContent;
  4161. }
  4162. child = child.nextSibling;
  4163. }
  4164. return result;
  4165. };
  4166. Tools.ToDegrees = function (angle) {
  4167. return angle * 180 / Math.PI;
  4168. };
  4169. Tools.ToRadians = function (angle) {
  4170. return angle * Math.PI / 180;
  4171. };
  4172. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4173. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4174. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4175. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4176. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4177. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4178. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4179. }
  4180. return {
  4181. minimum: minimum,
  4182. maximum: maximum
  4183. };
  4184. };
  4185. Tools.ExtractMinAndMax = function (positions, start, count) {
  4186. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4187. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4188. for (var index = start; index < start + count; index++) {
  4189. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4190. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4191. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4192. }
  4193. return {
  4194. minimum: minimum,
  4195. maximum: maximum
  4196. };
  4197. };
  4198. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4199. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4200. return undefined;
  4201. return Array.isArray(obj) ? obj : [obj];
  4202. };
  4203. // Misc.
  4204. Tools.GetPointerPrefix = function () {
  4205. var eventPrefix = "pointer";
  4206. // Check if hand.js is referenced or if the browser natively supports pointer events
  4207. if (!navigator.pointerEnabled) {
  4208. eventPrefix = "mouse";
  4209. }
  4210. return eventPrefix;
  4211. };
  4212. Tools.QueueNewFrame = function (func) {
  4213. if (window.requestAnimationFrame)
  4214. window.requestAnimationFrame(func);
  4215. else if (window.msRequestAnimationFrame)
  4216. window.msRequestAnimationFrame(func);
  4217. else if (window.webkitRequestAnimationFrame)
  4218. window.webkitRequestAnimationFrame(func);
  4219. else if (window.mozRequestAnimationFrame)
  4220. window.mozRequestAnimationFrame(func);
  4221. else if (window.oRequestAnimationFrame)
  4222. window.oRequestAnimationFrame(func);
  4223. else {
  4224. window.setTimeout(func, 16);
  4225. }
  4226. };
  4227. Tools.RequestFullscreen = function (element) {
  4228. if (element.requestFullscreen)
  4229. element.requestFullscreen();
  4230. else if (element.msRequestFullscreen)
  4231. element.msRequestFullscreen();
  4232. else if (element.webkitRequestFullscreen)
  4233. element.webkitRequestFullscreen();
  4234. else if (element.mozRequestFullScreen)
  4235. element.mozRequestFullScreen();
  4236. };
  4237. Tools.ExitFullscreen = function () {
  4238. if (document.exitFullscreen) {
  4239. document.exitFullscreen();
  4240. }
  4241. else if (document.mozCancelFullScreen) {
  4242. document.mozCancelFullScreen();
  4243. }
  4244. else if (document.webkitCancelFullScreen) {
  4245. document.webkitCancelFullScreen();
  4246. }
  4247. else if (document.msCancelFullScreen) {
  4248. document.msCancelFullScreen();
  4249. }
  4250. };
  4251. // External files
  4252. Tools.CleanUrl = function (url) {
  4253. url = url.replace(/#/mg, "%23");
  4254. return url;
  4255. };
  4256. Tools.LoadImage = function (url, onload, onerror, database) {
  4257. url = Tools.CleanUrl(url);
  4258. var img = new Image();
  4259. if (url.substr(0, 5) !== "data:")
  4260. img.crossOrigin = 'anonymous';
  4261. img.onload = function () {
  4262. onload(img);
  4263. };
  4264. img.onerror = function (err) {
  4265. onerror(img, err);
  4266. };
  4267. var noIndexedDB = function () {
  4268. img.src = url;
  4269. };
  4270. var loadFromIndexedDB = function () {
  4271. database.loadImageFromDB(url, img);
  4272. };
  4273. //ANY database to do!
  4274. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  4275. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4276. }
  4277. else {
  4278. if (url.indexOf("file:") === -1) {
  4279. noIndexedDB();
  4280. }
  4281. else {
  4282. try {
  4283. var textureName = url.substring(5);
  4284. var blobURL;
  4285. try {
  4286. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4287. }
  4288. catch (ex) {
  4289. // Chrome doesn't support oneTimeOnly parameter
  4290. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4291. }
  4292. img.src = blobURL;
  4293. }
  4294. catch (e) {
  4295. Tools.Log("Error while trying to load texture: " + textureName);
  4296. img.src = null;
  4297. }
  4298. }
  4299. }
  4300. return img;
  4301. };
  4302. //ANY
  4303. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4304. url = Tools.CleanUrl(url);
  4305. var noIndexedDB = function () {
  4306. var request = new XMLHttpRequest();
  4307. var loadUrl = Tools.BaseUrl + url;
  4308. request.open('GET', loadUrl, true);
  4309. if (useArrayBuffer) {
  4310. request.responseType = "arraybuffer";
  4311. }
  4312. request.onprogress = progressCallBack;
  4313. request.onreadystatechange = function () {
  4314. if (request.readyState === 4) {
  4315. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4316. callback(!useArrayBuffer ? request.responseText : request.response);
  4317. }
  4318. else {
  4319. if (onError) {
  4320. onError();
  4321. }
  4322. else {
  4323. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4324. }
  4325. }
  4326. }
  4327. };
  4328. request.send(null);
  4329. };
  4330. var loadFromIndexedDB = function () {
  4331. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4332. };
  4333. if (url.indexOf("file:") !== -1) {
  4334. var fileName = url.substring(5);
  4335. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4336. }
  4337. else {
  4338. // Caching all files
  4339. if (database && database.enableSceneOffline) {
  4340. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4341. }
  4342. else {
  4343. noIndexedDB();
  4344. }
  4345. }
  4346. };
  4347. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4348. var reader = new FileReader();
  4349. reader.onload = function (e) {
  4350. //target doesn't have result from ts 1.3
  4351. callback(e.target['result']);
  4352. };
  4353. reader.onprogress = progressCallback;
  4354. reader.readAsDataURL(fileToLoad);
  4355. };
  4356. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4357. var reader = new FileReader();
  4358. reader.onerror = function (e) {
  4359. Tools.Log("Error while reading file: " + fileToLoad.name);
  4360. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  4361. };
  4362. reader.onload = function (e) {
  4363. //target doesn't have result from ts 1.3
  4364. callback(e.target['result']);
  4365. };
  4366. reader.onprogress = progressCallBack;
  4367. if (!useArrayBuffer) {
  4368. // Asynchronous read
  4369. reader.readAsText(fileToLoad);
  4370. }
  4371. else {
  4372. reader.readAsArrayBuffer(fileToLoad);
  4373. }
  4374. };
  4375. // Misc.
  4376. Tools.Clamp = function (value, min, max) {
  4377. if (min === void 0) { min = 0; }
  4378. if (max === void 0) { max = 1; }
  4379. return Math.min(max, Math.max(min, value));
  4380. };
  4381. // Returns -1 when value is a negative number and
  4382. // +1 when value is a positive number.
  4383. Tools.Sign = function (value) {
  4384. value = +value; // convert to a number
  4385. if (value === 0 || isNaN(value))
  4386. return value;
  4387. return value > 0 ? 1 : -1;
  4388. };
  4389. Tools.Format = function (value, decimals) {
  4390. if (decimals === void 0) { decimals = 2; }
  4391. return value.toFixed(decimals);
  4392. };
  4393. Tools.CheckExtends = function (v, min, max) {
  4394. if (v.x < min.x)
  4395. min.x = v.x;
  4396. if (v.y < min.y)
  4397. min.y = v.y;
  4398. if (v.z < min.z)
  4399. min.z = v.z;
  4400. if (v.x > max.x)
  4401. max.x = v.x;
  4402. if (v.y > max.y)
  4403. max.y = v.y;
  4404. if (v.z > max.z)
  4405. max.z = v.z;
  4406. };
  4407. Tools.WithinEpsilon = function (a, b, epsilon) {
  4408. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4409. var num = a - b;
  4410. return -epsilon <= num && num <= epsilon;
  4411. };
  4412. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4413. for (var prop in source) {
  4414. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4415. continue;
  4416. }
  4417. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4418. continue;
  4419. }
  4420. var sourceValue = source[prop];
  4421. var typeOfSourceValue = typeof sourceValue;
  4422. if (typeOfSourceValue === "function") {
  4423. continue;
  4424. }
  4425. if (typeOfSourceValue === "object") {
  4426. if (sourceValue instanceof Array) {
  4427. destination[prop] = [];
  4428. if (sourceValue.length > 0) {
  4429. if (typeof sourceValue[0] == "object") {
  4430. for (var index = 0; index < sourceValue.length; index++) {
  4431. var clonedValue = cloneValue(sourceValue[index], destination);
  4432. if (destination[prop].indexOf(clonedValue) === -1) {
  4433. destination[prop].push(clonedValue);
  4434. }
  4435. }
  4436. }
  4437. else {
  4438. destination[prop] = sourceValue.slice(0);
  4439. }
  4440. }
  4441. }
  4442. else {
  4443. destination[prop] = cloneValue(sourceValue, destination);
  4444. }
  4445. }
  4446. else {
  4447. destination[prop] = sourceValue;
  4448. }
  4449. }
  4450. };
  4451. Tools.IsEmpty = function (obj) {
  4452. for (var i in obj) {
  4453. return false;
  4454. }
  4455. return true;
  4456. };
  4457. Tools.RegisterTopRootEvents = function (events) {
  4458. for (var index = 0; index < events.length; index++) {
  4459. var event = events[index];
  4460. window.addEventListener(event.name, event.handler, false);
  4461. try {
  4462. if (window.parent) {
  4463. window.parent.addEventListener(event.name, event.handler, false);
  4464. }
  4465. }
  4466. catch (e) {
  4467. }
  4468. }
  4469. };
  4470. Tools.UnregisterTopRootEvents = function (events) {
  4471. for (var index = 0; index < events.length; index++) {
  4472. var event = events[index];
  4473. window.removeEventListener(event.name, event.handler);
  4474. try {
  4475. if (window.parent) {
  4476. window.parent.removeEventListener(event.name, event.handler);
  4477. }
  4478. }
  4479. catch (e) {
  4480. }
  4481. }
  4482. };
  4483. Tools.DumpFramebuffer = function (width, height, engine) {
  4484. // Read the contents of the framebuffer
  4485. var numberOfChannelsByLine = width * 4;
  4486. var halfHeight = height / 2;
  4487. //Reading datas from WebGL
  4488. var data = engine.readPixels(0, 0, width, height);
  4489. for (var i = 0; i < halfHeight; i++) {
  4490. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4491. var currentCell = j + i * numberOfChannelsByLine;
  4492. var targetLine = height - i - 1;
  4493. var targetCell = j + targetLine * numberOfChannelsByLine;
  4494. var temp = data[currentCell];
  4495. data[currentCell] = data[targetCell];
  4496. data[targetCell] = temp;
  4497. }
  4498. }
  4499. // Create a 2D canvas to store the result
  4500. if (!screenshotCanvas) {
  4501. screenshotCanvas = document.createElement('canvas');
  4502. }
  4503. screenshotCanvas.width = width;
  4504. screenshotCanvas.height = height;
  4505. var context = screenshotCanvas.getContext('2d');
  4506. // Copy the pixels to a 2D canvas
  4507. var imageData = context.createImageData(width, height);
  4508. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4509. var castData = imageData.data;
  4510. castData.set(data);
  4511. context.putImageData(imageData, 0, 0);
  4512. var base64Image = screenshotCanvas.toDataURL();
  4513. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4514. if (("download" in document.createElement("a"))) {
  4515. var a = window.document.createElement("a");
  4516. a.href = base64Image;
  4517. var date = new Date();
  4518. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4519. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4520. window.document.body.appendChild(a);
  4521. a.addEventListener("click", function () {
  4522. a.parentElement.removeChild(a);
  4523. });
  4524. a.click();
  4525. }
  4526. else {
  4527. var newWindow = window.open("");
  4528. var img = newWindow.document.createElement("img");
  4529. img.src = base64Image;
  4530. newWindow.document.body.appendChild(img);
  4531. }
  4532. };
  4533. Tools.CreateScreenshot = function (engine, camera, size) {
  4534. var width;
  4535. var height;
  4536. var scene = camera.getScene();
  4537. var previousCamera = null;
  4538. if (scene.activeCamera !== camera) {
  4539. previousCamera = scene.activeCamera;
  4540. scene.activeCamera = camera;
  4541. }
  4542. //If a precision value is specified
  4543. if (size.precision) {
  4544. width = Math.round(engine.getRenderWidth() * size.precision);
  4545. height = Math.round(width / engine.getAspectRatio(camera));
  4546. size = { width: width, height: height };
  4547. }
  4548. else if (size.width && size.height) {
  4549. width = size.width;
  4550. height = size.height;
  4551. }
  4552. else if (size.width && !size.height) {
  4553. width = size.width;
  4554. height = Math.round(width / engine.getAspectRatio(camera));
  4555. size = { width: width, height: height };
  4556. }
  4557. else if (size.height && !size.width) {
  4558. height = size.height;
  4559. width = Math.round(height * engine.getAspectRatio(camera));
  4560. size = { width: width, height: height };
  4561. }
  4562. else if (!isNaN(size)) {
  4563. height = size;
  4564. width = size;
  4565. }
  4566. else {
  4567. Tools.Error("Invalid 'size' parameter !");
  4568. return;
  4569. }
  4570. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4571. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4572. texture.renderList = scene.meshes;
  4573. texture.onAfterRender = function () {
  4574. Tools.DumpFramebuffer(width, height, engine);
  4575. };
  4576. scene.incrementRenderId();
  4577. texture.render(true);
  4578. texture.dispose();
  4579. if (previousCamera) {
  4580. scene.activeCamera = previousCamera;
  4581. }
  4582. };
  4583. // XHR response validator for local file scenario
  4584. Tools.ValidateXHRData = function (xhr, dataType) {
  4585. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4586. if (dataType === void 0) { dataType = 7; }
  4587. try {
  4588. if (dataType & 1) {
  4589. if (xhr.responseText && xhr.responseText.length > 0) {
  4590. return true;
  4591. }
  4592. else if (dataType === 1) {
  4593. return false;
  4594. }
  4595. }
  4596. if (dataType & 2) {
  4597. // Check header width and height since there is no "TGA" magic number
  4598. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4599. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4600. return true;
  4601. }
  4602. else if (dataType === 2) {
  4603. return false;
  4604. }
  4605. }
  4606. if (dataType & 4) {
  4607. // Check for the "DDS" magic number
  4608. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4609. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4610. return true;
  4611. }
  4612. else {
  4613. return false;
  4614. }
  4615. }
  4616. }
  4617. catch (e) {
  4618. }
  4619. return false;
  4620. };
  4621. Object.defineProperty(Tools, "NoneLogLevel", {
  4622. get: function () {
  4623. return Tools._NoneLogLevel;
  4624. },
  4625. enumerable: true,
  4626. configurable: true
  4627. });
  4628. Object.defineProperty(Tools, "MessageLogLevel", {
  4629. get: function () {
  4630. return Tools._MessageLogLevel;
  4631. },
  4632. enumerable: true,
  4633. configurable: true
  4634. });
  4635. Object.defineProperty(Tools, "WarningLogLevel", {
  4636. get: function () {
  4637. return Tools._WarningLogLevel;
  4638. },
  4639. enumerable: true,
  4640. configurable: true
  4641. });
  4642. Object.defineProperty(Tools, "ErrorLogLevel", {
  4643. get: function () {
  4644. return Tools._ErrorLogLevel;
  4645. },
  4646. enumerable: true,
  4647. configurable: true
  4648. });
  4649. Object.defineProperty(Tools, "AllLogLevel", {
  4650. get: function () {
  4651. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4652. },
  4653. enumerable: true,
  4654. configurable: true
  4655. });
  4656. Tools._AddLogEntry = function (entry) {
  4657. Tools._LogCache = entry + Tools._LogCache;
  4658. if (Tools.OnNewCacheEntry) {
  4659. Tools.OnNewCacheEntry(entry);
  4660. }
  4661. };
  4662. Tools._FormatMessage = function (message) {
  4663. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4664. var date = new Date();
  4665. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4666. };
  4667. Tools._LogDisabled = function (message) {
  4668. // nothing to do
  4669. };
  4670. Tools._LogEnabled = function (message) {
  4671. var formattedMessage = Tools._FormatMessage(message);
  4672. console.log("BJS - " + formattedMessage);
  4673. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4674. Tools._AddLogEntry(entry);
  4675. };
  4676. Tools._WarnDisabled = function (message) {
  4677. // nothing to do
  4678. };
  4679. Tools._WarnEnabled = function (message) {
  4680. var formattedMessage = Tools._FormatMessage(message);
  4681. console.warn("BJS - " + formattedMessage);
  4682. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4683. Tools._AddLogEntry(entry);
  4684. };
  4685. Tools._ErrorDisabled = function (message) {
  4686. // nothing to do
  4687. };
  4688. Tools._ErrorEnabled = function (message) {
  4689. var formattedMessage = Tools._FormatMessage(message);
  4690. console.error("BJS - " + formattedMessage);
  4691. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4692. Tools._AddLogEntry(entry);
  4693. };
  4694. Object.defineProperty(Tools, "LogCache", {
  4695. get: function () {
  4696. return Tools._LogCache;
  4697. },
  4698. enumerable: true,
  4699. configurable: true
  4700. });
  4701. Object.defineProperty(Tools, "LogLevels", {
  4702. set: function (level) {
  4703. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4704. Tools.Log = Tools._LogEnabled;
  4705. }
  4706. else {
  4707. Tools.Log = Tools._LogDisabled;
  4708. }
  4709. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4710. Tools.Warn = Tools._WarnEnabled;
  4711. }
  4712. else {
  4713. Tools.Warn = Tools._WarnDisabled;
  4714. }
  4715. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4716. Tools.Error = Tools._ErrorEnabled;
  4717. }
  4718. else {
  4719. Tools.Error = Tools._ErrorDisabled;
  4720. }
  4721. },
  4722. enumerable: true,
  4723. configurable: true
  4724. });
  4725. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4726. get: function () {
  4727. return Tools._PerformanceNoneLogLevel;
  4728. },
  4729. enumerable: true,
  4730. configurable: true
  4731. });
  4732. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4733. get: function () {
  4734. return Tools._PerformanceUserMarkLogLevel;
  4735. },
  4736. enumerable: true,
  4737. configurable: true
  4738. });
  4739. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4740. get: function () {
  4741. return Tools._PerformanceConsoleLogLevel;
  4742. },
  4743. enumerable: true,
  4744. configurable: true
  4745. });
  4746. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4747. set: function (level) {
  4748. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4749. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4750. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4751. return;
  4752. }
  4753. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4754. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4755. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4756. return;
  4757. }
  4758. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4759. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4760. },
  4761. enumerable: true,
  4762. configurable: true
  4763. });
  4764. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4765. };
  4766. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4767. };
  4768. Tools._StartUserMark = function (counterName, condition) {
  4769. if (condition === void 0) { condition = true; }
  4770. if (!condition || !Tools._performance.mark) {
  4771. return;
  4772. }
  4773. Tools._performance.mark(counterName + "-Begin");
  4774. };
  4775. Tools._EndUserMark = function (counterName, condition) {
  4776. if (condition === void 0) { condition = true; }
  4777. if (!condition || !Tools._performance.mark) {
  4778. return;
  4779. }
  4780. Tools._performance.mark(counterName + "-End");
  4781. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4782. };
  4783. Tools._StartPerformanceConsole = function (counterName, condition) {
  4784. if (condition === void 0) { condition = true; }
  4785. if (!condition) {
  4786. return;
  4787. }
  4788. Tools._StartUserMark(counterName, condition);
  4789. if (console.time) {
  4790. console.time(counterName);
  4791. }
  4792. };
  4793. Tools._EndPerformanceConsole = function (counterName, condition) {
  4794. if (condition === void 0) { condition = true; }
  4795. if (!condition) {
  4796. return;
  4797. }
  4798. Tools._EndUserMark(counterName, condition);
  4799. if (console.time) {
  4800. console.timeEnd(counterName);
  4801. }
  4802. };
  4803. Object.defineProperty(Tools, "Now", {
  4804. get: function () {
  4805. if (window.performance && window.performance.now) {
  4806. return window.performance.now();
  4807. }
  4808. return new Date().getTime();
  4809. },
  4810. enumerable: true,
  4811. configurable: true
  4812. });
  4813. // Deprecated
  4814. Tools.GetFps = function () {
  4815. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4816. return 0;
  4817. };
  4818. Tools.BaseUrl = "";
  4819. Tools.GetExponantOfTwo = function (value, max) {
  4820. var count = 1;
  4821. do {
  4822. count *= 2;
  4823. } while (count < value);
  4824. if (count > max)
  4825. count = max;
  4826. return count;
  4827. };
  4828. // Logs
  4829. Tools._NoneLogLevel = 0;
  4830. Tools._MessageLogLevel = 1;
  4831. Tools._WarningLogLevel = 2;
  4832. Tools._ErrorLogLevel = 4;
  4833. Tools._LogCache = "";
  4834. Tools.Log = Tools._LogEnabled;
  4835. Tools.Warn = Tools._WarnEnabled;
  4836. Tools.Error = Tools._ErrorEnabled;
  4837. // Performances
  4838. Tools._PerformanceNoneLogLevel = 0;
  4839. Tools._PerformanceUserMarkLogLevel = 1;
  4840. Tools._PerformanceConsoleLogLevel = 2;
  4841. Tools._performance = window.performance;
  4842. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4843. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4844. return Tools;
  4845. })();
  4846. BABYLON.Tools = Tools;
  4847. /**
  4848. * An implementation of a loop for asynchronous functions.
  4849. */
  4850. var AsyncLoop = (function () {
  4851. /**
  4852. * Constroctor.
  4853. * @param iterations the number of iterations.
  4854. * @param _fn the function to run each iteration
  4855. * @param _successCallback the callback that will be called upon succesful execution
  4856. * @param offset starting offset.
  4857. */
  4858. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4859. if (offset === void 0) { offset = 0; }
  4860. this.iterations = iterations;
  4861. this._fn = _fn;
  4862. this._successCallback = _successCallback;
  4863. this.index = offset - 1;
  4864. this._done = false;
  4865. }
  4866. /**
  4867. * Execute the next iteration. Must be called after the last iteration was finished.
  4868. */
  4869. AsyncLoop.prototype.executeNext = function () {
  4870. if (!this._done) {
  4871. if (this.index + 1 < this.iterations) {
  4872. ++this.index;
  4873. this._fn(this);
  4874. }
  4875. else {
  4876. this.breakLoop();
  4877. }
  4878. }
  4879. };
  4880. /**
  4881. * Break the loop and run the success callback.
  4882. */
  4883. AsyncLoop.prototype.breakLoop = function () {
  4884. this._done = true;
  4885. this._successCallback();
  4886. };
  4887. /**
  4888. * Helper function
  4889. */
  4890. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4891. if (offset === void 0) { offset = 0; }
  4892. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4893. loop.executeNext();
  4894. return loop;
  4895. };
  4896. /**
  4897. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4898. * @param iterations total number of iterations
  4899. * @param syncedIterations number of synchronous iterations in each async iteration.
  4900. * @param fn the function to call each iteration.
  4901. * @param callback a success call back that will be called when iterating stops.
  4902. * @param breakFunction a break condition (optional)
  4903. * @param timeout timeout settings for the setTimeout function. default - 0.
  4904. * @constructor
  4905. */
  4906. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4907. if (timeout === void 0) { timeout = 0; }
  4908. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4909. if (breakFunction && breakFunction())
  4910. loop.breakLoop();
  4911. else {
  4912. setTimeout(function () {
  4913. for (var i = 0; i < syncedIterations; ++i) {
  4914. var iteration = (loop.index * syncedIterations) + i;
  4915. if (iteration >= iterations)
  4916. break;
  4917. fn(iteration);
  4918. if (breakFunction && breakFunction()) {
  4919. loop.breakLoop();
  4920. break;
  4921. }
  4922. }
  4923. loop.executeNext();
  4924. }, timeout);
  4925. }
  4926. }, callback);
  4927. };
  4928. return AsyncLoop;
  4929. })();
  4930. BABYLON.AsyncLoop = AsyncLoop;
  4931. })(BABYLON || (BABYLON = {}));
  4932. //# sourceMappingURL=babylon.tools.js.map
  4933. var BABYLON;
  4934. (function (BABYLON) {
  4935. var _DepthCullingState = (function () {
  4936. function _DepthCullingState() {
  4937. this._isDepthTestDirty = false;
  4938. this._isDepthMaskDirty = false;
  4939. this._isDepthFuncDirty = false;
  4940. this._isCullFaceDirty = false;
  4941. this._isCullDirty = false;
  4942. this._isZOffsetDirty = false;
  4943. }
  4944. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4945. get: function () {
  4946. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4947. },
  4948. enumerable: true,
  4949. configurable: true
  4950. });
  4951. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4952. get: function () {
  4953. return this._zOffset;
  4954. },
  4955. set: function (value) {
  4956. if (this._zOffset === value) {
  4957. return;
  4958. }
  4959. this._zOffset = value;
  4960. this._isZOffsetDirty = true;
  4961. },
  4962. enumerable: true,
  4963. configurable: true
  4964. });
  4965. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4966. get: function () {
  4967. return this._cullFace;
  4968. },
  4969. set: function (value) {
  4970. if (this._cullFace === value) {
  4971. return;
  4972. }
  4973. this._cullFace = value;
  4974. this._isCullFaceDirty = true;
  4975. },
  4976. enumerable: true,
  4977. configurable: true
  4978. });
  4979. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  4980. get: function () {
  4981. return this._cull;
  4982. },
  4983. set: function (value) {
  4984. if (this._cull === value) {
  4985. return;
  4986. }
  4987. this._cull = value;
  4988. this._isCullDirty = true;
  4989. },
  4990. enumerable: true,
  4991. configurable: true
  4992. });
  4993. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  4994. get: function () {
  4995. return this._depthFunc;
  4996. },
  4997. set: function (value) {
  4998. if (this._depthFunc === value) {
  4999. return;
  5000. }
  5001. this._depthFunc = value;
  5002. this._isDepthFuncDirty = true;
  5003. },
  5004. enumerable: true,
  5005. configurable: true
  5006. });
  5007. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5008. get: function () {
  5009. return this._depthMask;
  5010. },
  5011. set: function (value) {
  5012. if (this._depthMask === value) {
  5013. return;
  5014. }
  5015. this._depthMask = value;
  5016. this._isDepthMaskDirty = true;
  5017. },
  5018. enumerable: true,
  5019. configurable: true
  5020. });
  5021. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5022. get: function () {
  5023. return this._depthTest;
  5024. },
  5025. set: function (value) {
  5026. if (this._depthTest === value) {
  5027. return;
  5028. }
  5029. this._depthTest = value;
  5030. this._isDepthTestDirty = true;
  5031. },
  5032. enumerable: true,
  5033. configurable: true
  5034. });
  5035. _DepthCullingState.prototype.reset = function () {
  5036. this._depthMask = true;
  5037. this._depthTest = true;
  5038. this._depthFunc = null;
  5039. this._cull = null;
  5040. this._cullFace = null;
  5041. this._zOffset = 0;
  5042. this._isDepthTestDirty = true;
  5043. this._isDepthMaskDirty = true;
  5044. this._isDepthFuncDirty = false;
  5045. this._isCullFaceDirty = false;
  5046. this._isCullDirty = false;
  5047. this._isZOffsetDirty = false;
  5048. };
  5049. _DepthCullingState.prototype.apply = function (gl) {
  5050. if (!this.isDirty) {
  5051. return;
  5052. }
  5053. // Cull
  5054. if (this._isCullDirty) {
  5055. if (this.cull) {
  5056. gl.enable(gl.CULL_FACE);
  5057. }
  5058. else {
  5059. gl.disable(gl.CULL_FACE);
  5060. }
  5061. this._isCullDirty = false;
  5062. }
  5063. // Cull face
  5064. if (this._isCullFaceDirty) {
  5065. gl.cullFace(this.cullFace);
  5066. this._isCullFaceDirty = false;
  5067. }
  5068. // Depth mask
  5069. if (this._isDepthMaskDirty) {
  5070. gl.depthMask(this.depthMask);
  5071. this._isDepthMaskDirty = false;
  5072. }
  5073. // Depth test
  5074. if (this._isDepthTestDirty) {
  5075. if (this.depthTest) {
  5076. gl.enable(gl.DEPTH_TEST);
  5077. }
  5078. else {
  5079. gl.disable(gl.DEPTH_TEST);
  5080. }
  5081. this._isDepthTestDirty = false;
  5082. }
  5083. // Depth func
  5084. if (this._isDepthFuncDirty) {
  5085. gl.depthFunc(this.depthFunc);
  5086. this._isDepthFuncDirty = false;
  5087. }
  5088. // zOffset
  5089. if (this._isZOffsetDirty) {
  5090. if (this.zOffset) {
  5091. gl.enable(gl.POLYGON_OFFSET_FILL);
  5092. gl.polygonOffset(this.zOffset, 0);
  5093. }
  5094. else {
  5095. gl.disable(gl.POLYGON_OFFSET_FILL);
  5096. }
  5097. this._isZOffsetDirty = false;
  5098. }
  5099. };
  5100. return _DepthCullingState;
  5101. })();
  5102. BABYLON._DepthCullingState = _DepthCullingState;
  5103. var _AlphaState = (function () {
  5104. function _AlphaState() {
  5105. this._isAlphaBlendDirty = false;
  5106. this._isBlendFunctionParametersDirty = false;
  5107. this._alphaBlend = false;
  5108. this._blendFunctionParameters = new Array(4);
  5109. }
  5110. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5111. get: function () {
  5112. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5113. },
  5114. enumerable: true,
  5115. configurable: true
  5116. });
  5117. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5118. get: function () {
  5119. return this._alphaBlend;
  5120. },
  5121. set: function (value) {
  5122. if (this._alphaBlend === value) {
  5123. return;
  5124. }
  5125. this._alphaBlend = value;
  5126. this._isAlphaBlendDirty = true;
  5127. },
  5128. enumerable: true,
  5129. configurable: true
  5130. });
  5131. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5132. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  5133. return;
  5134. }
  5135. this._blendFunctionParameters[0] = value0;
  5136. this._blendFunctionParameters[1] = value1;
  5137. this._blendFunctionParameters[2] = value2;
  5138. this._blendFunctionParameters[3] = value3;
  5139. this._isBlendFunctionParametersDirty = true;
  5140. };
  5141. _AlphaState.prototype.reset = function () {
  5142. this._alphaBlend = false;
  5143. this._blendFunctionParameters[0] = null;
  5144. this._blendFunctionParameters[1] = null;
  5145. this._blendFunctionParameters[2] = null;
  5146. this._blendFunctionParameters[3] = null;
  5147. this._isAlphaBlendDirty = true;
  5148. this._isBlendFunctionParametersDirty = false;
  5149. };
  5150. _AlphaState.prototype.apply = function (gl) {
  5151. if (!this.isDirty) {
  5152. return;
  5153. }
  5154. // Alpha blend
  5155. if (this._isAlphaBlendDirty) {
  5156. if (this._alphaBlend) {
  5157. gl.enable(gl.BLEND);
  5158. }
  5159. else {
  5160. gl.disable(gl.BLEND);
  5161. }
  5162. this._isAlphaBlendDirty = false;
  5163. }
  5164. // Alpha function
  5165. if (this._isBlendFunctionParametersDirty) {
  5166. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5167. this._isBlendFunctionParametersDirty = false;
  5168. }
  5169. };
  5170. return _AlphaState;
  5171. })();
  5172. BABYLON._AlphaState = _AlphaState;
  5173. var compileShader = function (gl, source, type, defines) {
  5174. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5175. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5176. gl.compileShader(shader);
  5177. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5178. throw new Error(gl.getShaderInfoLog(shader));
  5179. }
  5180. return shader;
  5181. };
  5182. var getWebGLTextureType = function (gl, type) {
  5183. var textureType = gl.UNSIGNED_BYTE;
  5184. if (type === Engine.TEXTURETYPE_FLOAT)
  5185. textureType = gl.FLOAT;
  5186. return textureType;
  5187. };
  5188. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5189. var magFilter = gl.NEAREST;
  5190. var minFilter = gl.NEAREST;
  5191. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5192. magFilter = gl.LINEAR;
  5193. if (generateMipMaps) {
  5194. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5195. }
  5196. else {
  5197. minFilter = gl.LINEAR;
  5198. }
  5199. }
  5200. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5201. magFilter = gl.LINEAR;
  5202. if (generateMipMaps) {
  5203. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5204. }
  5205. else {
  5206. minFilter = gl.LINEAR;
  5207. }
  5208. }
  5209. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5210. magFilter = gl.NEAREST;
  5211. if (generateMipMaps) {
  5212. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5213. }
  5214. else {
  5215. minFilter = gl.NEAREST;
  5216. }
  5217. }
  5218. return {
  5219. min: minFilter,
  5220. mag: magFilter
  5221. };
  5222. };
  5223. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5224. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5225. var engine = scene.getEngine();
  5226. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5227. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5228. gl.bindTexture(gl.TEXTURE_2D, texture);
  5229. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5230. texture._baseWidth = width;
  5231. texture._baseHeight = height;
  5232. texture._width = potWidth;
  5233. texture._height = potHeight;
  5234. texture.isReady = true;
  5235. processFunction(potWidth, potHeight);
  5236. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5237. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5239. if (!noMipmap && !isCompressed) {
  5240. gl.generateMipmap(gl.TEXTURE_2D);
  5241. }
  5242. gl.bindTexture(gl.TEXTURE_2D, null);
  5243. engine._activeTexturesCache = [];
  5244. scene._removePendingData(texture);
  5245. };
  5246. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5247. var onload = function () {
  5248. loadedImages[index] = img;
  5249. loadedImages._internalCount++;
  5250. scene._removePendingData(img);
  5251. if (loadedImages._internalCount === 6) {
  5252. onfinish(loadedImages);
  5253. }
  5254. };
  5255. var onerror = function () {
  5256. scene._removePendingData(img);
  5257. };
  5258. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5259. scene._addPendingData(img);
  5260. };
  5261. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5262. var loadedImages = [];
  5263. loadedImages._internalCount = 0;
  5264. for (var index = 0; index < 6; index++) {
  5265. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5266. }
  5267. };
  5268. var EngineCapabilities = (function () {
  5269. function EngineCapabilities() {
  5270. }
  5271. return EngineCapabilities;
  5272. })();
  5273. BABYLON.EngineCapabilities = EngineCapabilities;
  5274. /**
  5275. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5276. */
  5277. var Engine = (function () {
  5278. /**
  5279. * @constructor
  5280. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5281. * @param {boolean} [antialias] - enable antialias
  5282. * @param options - further options to be sent to the getContext function
  5283. */
  5284. function Engine(canvas, antialias, options) {
  5285. var _this = this;
  5286. // Public members
  5287. this.isFullscreen = false;
  5288. this.isPointerLock = false;
  5289. this.cullBackFaces = true;
  5290. this.renderEvenInBackground = true;
  5291. this.scenes = new Array();
  5292. this._windowIsBackground = false;
  5293. this._loadingDivBackgroundColor = "black";
  5294. this._drawCalls = 0;
  5295. this._renderingQueueLaunched = false;
  5296. this._activeRenderLoops = [];
  5297. // FPS
  5298. this.fpsRange = 60;
  5299. this.previousFramesDuration = [];
  5300. this.fps = 60;
  5301. this.deltaTime = 0;
  5302. // States
  5303. this._depthCullingState = new _DepthCullingState();
  5304. this._alphaState = new _AlphaState();
  5305. this._alphaMode = Engine.ALPHA_DISABLE;
  5306. // Cache
  5307. this._loadedTexturesCache = new Array();
  5308. this._activeTexturesCache = new Array();
  5309. this._compiledEffects = {};
  5310. this._uintIndicesCurrentlySet = false;
  5311. this._renderingCanvas = canvas;
  5312. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5313. options = options || {};
  5314. options.antialias = antialias;
  5315. try {
  5316. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  5317. }
  5318. catch (e) {
  5319. throw new Error("WebGL not supported");
  5320. }
  5321. if (!this._gl) {
  5322. throw new Error("WebGL not supported");
  5323. }
  5324. this._onBlur = function () {
  5325. _this._windowIsBackground = true;
  5326. };
  5327. this._onFocus = function () {
  5328. _this._windowIsBackground = false;
  5329. };
  5330. window.addEventListener("blur", this._onBlur);
  5331. window.addEventListener("focus", this._onFocus);
  5332. // Viewport
  5333. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5334. this.resize();
  5335. // Caps
  5336. this._caps = new EngineCapabilities();
  5337. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5338. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5339. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5340. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5341. // Infos
  5342. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5343. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5344. if (rendererInfo != null) {
  5345. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5346. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5347. }
  5348. if (!this._glVendor) {
  5349. this._glVendor = "Unknown vendor";
  5350. }
  5351. if (!this._glRenderer) {
  5352. this._glRenderer = "Unknown renderer";
  5353. }
  5354. // Extensions
  5355. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5356. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5357. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5358. 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');
  5359. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5360. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5361. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5362. this._caps.highPrecisionShaderSupported = true;
  5363. if (this._gl.getShaderPrecisionFormat) {
  5364. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5365. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5366. }
  5367. // Depth buffer
  5368. this.setDepthBuffer(true);
  5369. this.setDepthFunctionToLessOrEqual();
  5370. this.setDepthWrite(true);
  5371. // Fullscreen
  5372. this._onFullscreenChange = function () {
  5373. if (document.fullscreen !== undefined) {
  5374. _this.isFullscreen = document.fullscreen;
  5375. }
  5376. else if (document.mozFullScreen !== undefined) {
  5377. _this.isFullscreen = document.mozFullScreen;
  5378. }
  5379. else if (document.webkitIsFullScreen !== undefined) {
  5380. _this.isFullscreen = document.webkitIsFullScreen;
  5381. }
  5382. else if (document.msIsFullScreen !== undefined) {
  5383. _this.isFullscreen = document.msIsFullScreen;
  5384. }
  5385. // Pointer lock
  5386. if (_this.isFullscreen && _this._pointerLockRequested) {
  5387. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  5388. if (canvas.requestPointerLock) {
  5389. canvas.requestPointerLock();
  5390. }
  5391. }
  5392. };
  5393. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5394. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5395. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5396. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5397. // Pointer lock
  5398. this._onPointerLockChange = function () {
  5399. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  5400. };
  5401. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5402. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5403. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5404. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5405. if (!Engine.audioEngine) {
  5406. Engine.audioEngine = new BABYLON.AudioEngine();
  5407. }
  5408. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5409. }
  5410. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5411. get: function () {
  5412. return Engine._ALPHA_DISABLE;
  5413. },
  5414. enumerable: true,
  5415. configurable: true
  5416. });
  5417. Object.defineProperty(Engine, "ALPHA_ADD", {
  5418. get: function () {
  5419. return Engine._ALPHA_ADD;
  5420. },
  5421. enumerable: true,
  5422. configurable: true
  5423. });
  5424. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5425. get: function () {
  5426. return Engine._ALPHA_COMBINE;
  5427. },
  5428. enumerable: true,
  5429. configurable: true
  5430. });
  5431. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5432. get: function () {
  5433. return Engine._DELAYLOADSTATE_NONE;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5439. get: function () {
  5440. return Engine._DELAYLOADSTATE_LOADED;
  5441. },
  5442. enumerable: true,
  5443. configurable: true
  5444. });
  5445. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5446. get: function () {
  5447. return Engine._DELAYLOADSTATE_LOADING;
  5448. },
  5449. enumerable: true,
  5450. configurable: true
  5451. });
  5452. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5453. get: function () {
  5454. return Engine._DELAYLOADSTATE_NOTLOADED;
  5455. },
  5456. enumerable: true,
  5457. configurable: true
  5458. });
  5459. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5460. get: function () {
  5461. return Engine._TEXTUREFORMAT_ALPHA;
  5462. },
  5463. enumerable: true,
  5464. configurable: true
  5465. });
  5466. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5467. get: function () {
  5468. return Engine._TEXTUREFORMAT_LUMINANCE;
  5469. },
  5470. enumerable: true,
  5471. configurable: true
  5472. });
  5473. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5474. get: function () {
  5475. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5476. },
  5477. enumerable: true,
  5478. configurable: true
  5479. });
  5480. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5481. get: function () {
  5482. return Engine._TEXTUREFORMAT_RGB;
  5483. },
  5484. enumerable: true,
  5485. configurable: true
  5486. });
  5487. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5488. get: function () {
  5489. return Engine._TEXTUREFORMAT_RGBA;
  5490. },
  5491. enumerable: true,
  5492. configurable: true
  5493. });
  5494. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5495. get: function () {
  5496. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5497. },
  5498. enumerable: true,
  5499. configurable: true
  5500. });
  5501. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5502. get: function () {
  5503. return Engine._TEXTURETYPE_FLOAT;
  5504. },
  5505. enumerable: true,
  5506. configurable: true
  5507. });
  5508. Object.defineProperty(Engine, "Version", {
  5509. get: function () {
  5510. return "2.1.0 beta";
  5511. },
  5512. enumerable: true,
  5513. configurable: true
  5514. });
  5515. Engine.prototype._prepareWorkingCanvas = function () {
  5516. if (this._workingCanvas) {
  5517. return;
  5518. }
  5519. this._workingCanvas = document.createElement("canvas");
  5520. this._workingContext = this._workingCanvas.getContext("2d");
  5521. };
  5522. Engine.prototype.getGlInfo = function () {
  5523. return {
  5524. vendor: this._glVendor,
  5525. renderer: this._glRenderer,
  5526. version: this._glVersion
  5527. };
  5528. };
  5529. Engine.prototype.getAspectRatio = function (camera) {
  5530. var viewport = camera.viewport;
  5531. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5532. };
  5533. Engine.prototype.getRenderWidth = function () {
  5534. if (this._currentRenderTarget) {
  5535. return this._currentRenderTarget._width;
  5536. }
  5537. return this._renderingCanvas.width;
  5538. };
  5539. Engine.prototype.getRenderHeight = function () {
  5540. if (this._currentRenderTarget) {
  5541. return this._currentRenderTarget._height;
  5542. }
  5543. return this._renderingCanvas.height;
  5544. };
  5545. Engine.prototype.getRenderingCanvas = function () {
  5546. return this._renderingCanvas;
  5547. };
  5548. Engine.prototype.getRenderingCanvasClientRect = function () {
  5549. return this._renderingCanvas.getBoundingClientRect();
  5550. };
  5551. Engine.prototype.setHardwareScalingLevel = function (level) {
  5552. this._hardwareScalingLevel = level;
  5553. this.resize();
  5554. };
  5555. Engine.prototype.getHardwareScalingLevel = function () {
  5556. return this._hardwareScalingLevel;
  5557. };
  5558. Engine.prototype.getLoadedTexturesCache = function () {
  5559. return this._loadedTexturesCache;
  5560. };
  5561. Engine.prototype.getCaps = function () {
  5562. return this._caps;
  5563. };
  5564. Object.defineProperty(Engine.prototype, "drawCalls", {
  5565. get: function () {
  5566. return this._drawCalls;
  5567. },
  5568. enumerable: true,
  5569. configurable: true
  5570. });
  5571. // Methods
  5572. Engine.prototype.resetDrawCalls = function () {
  5573. this._drawCalls = 0;
  5574. };
  5575. Engine.prototype.setDepthFunctionToGreater = function () {
  5576. this._depthCullingState.depthFunc = this._gl.GREATER;
  5577. };
  5578. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5579. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5580. };
  5581. Engine.prototype.setDepthFunctionToLess = function () {
  5582. this._depthCullingState.depthFunc = this._gl.LESS;
  5583. };
  5584. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5585. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5586. };
  5587. /**
  5588. * stop executing a render loop function and remove it from the execution array
  5589. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5590. */
  5591. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5592. if (!renderFunction) {
  5593. this._activeRenderLoops = [];
  5594. return;
  5595. }
  5596. var index = this._activeRenderLoops.indexOf(renderFunction);
  5597. if (index >= 0) {
  5598. this._activeRenderLoops.splice(index, 1);
  5599. }
  5600. };
  5601. Engine.prototype._renderLoop = function () {
  5602. var _this = this;
  5603. var shouldRender = true;
  5604. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5605. shouldRender = false;
  5606. }
  5607. if (shouldRender) {
  5608. // Start new frame
  5609. this.beginFrame();
  5610. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5611. var renderFunction = this._activeRenderLoops[index];
  5612. renderFunction();
  5613. }
  5614. // Present
  5615. this.endFrame();
  5616. }
  5617. if (this._activeRenderLoops.length > 0) {
  5618. // Register new frame
  5619. BABYLON.Tools.QueueNewFrame(function () {
  5620. _this._renderLoop();
  5621. });
  5622. }
  5623. else {
  5624. this._renderingQueueLaunched = false;
  5625. }
  5626. };
  5627. /**
  5628. * Register and execute a render loop. The engine can have more than one render function.
  5629. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5630. * @example
  5631. * engine.runRenderLoop(function () {
  5632. * scene.render()
  5633. * })
  5634. */
  5635. Engine.prototype.runRenderLoop = function (renderFunction) {
  5636. var _this = this;
  5637. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5638. return;
  5639. }
  5640. this._activeRenderLoops.push(renderFunction);
  5641. if (!this._renderingQueueLaunched) {
  5642. this._renderingQueueLaunched = true;
  5643. BABYLON.Tools.QueueNewFrame(function () {
  5644. _this._renderLoop();
  5645. });
  5646. }
  5647. };
  5648. /**
  5649. * Toggle full screen mode.
  5650. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5651. */
  5652. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5653. if (this.isFullscreen) {
  5654. BABYLON.Tools.ExitFullscreen();
  5655. }
  5656. else {
  5657. this._pointerLockRequested = requestPointerLock;
  5658. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5659. }
  5660. };
  5661. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5662. this.applyStates();
  5663. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5664. if (this._depthCullingState.depthMask) {
  5665. this._gl.clearDepth(1.0);
  5666. }
  5667. var mode = 0;
  5668. if (backBuffer)
  5669. mode |= this._gl.COLOR_BUFFER_BIT;
  5670. if (depthStencil && this._depthCullingState.depthMask)
  5671. mode |= this._gl.DEPTH_BUFFER_BIT;
  5672. this._gl.clear(mode);
  5673. };
  5674. /**
  5675. * Set the WebGL's viewport
  5676. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5677. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5678. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5679. */
  5680. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5681. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5682. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5683. var x = viewport.x || 0;
  5684. var y = viewport.y || 0;
  5685. this._cachedViewport = viewport;
  5686. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5687. };
  5688. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5689. this._cachedViewport = null;
  5690. this._gl.viewport(x, y, width, height);
  5691. };
  5692. Engine.prototype.beginFrame = function () {
  5693. this._measureFps();
  5694. };
  5695. Engine.prototype.endFrame = function () {
  5696. //this.flushFramebuffer();
  5697. };
  5698. /**
  5699. * resize the view according to the canvas' size.
  5700. * @example
  5701. * window.addEventListener("resize", function () {
  5702. * engine.resize();
  5703. * });
  5704. */
  5705. Engine.prototype.resize = function () {
  5706. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5707. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5708. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5709. };
  5710. /**
  5711. * force a specific size of the canvas
  5712. * @param {number} width - the new canvas' width
  5713. * @param {number} height - the new canvas' height
  5714. */
  5715. Engine.prototype.setSize = function (width, height) {
  5716. this._renderingCanvas.width = width;
  5717. this._renderingCanvas.height = height;
  5718. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  5719. for (var index = 0; index < this.scenes.length; index++) {
  5720. var scene = this.scenes[index];
  5721. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5722. var cam = scene.cameras[camIndex];
  5723. cam._currentRenderId = 0;
  5724. }
  5725. }
  5726. };
  5727. Engine.prototype.bindFramebuffer = function (texture) {
  5728. this._currentRenderTarget = texture;
  5729. var gl = this._gl;
  5730. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5731. this._gl.viewport(0, 0, texture._width, texture._height);
  5732. this.wipeCaches();
  5733. };
  5734. Engine.prototype.unBindFramebuffer = function (texture) {
  5735. this._currentRenderTarget = null;
  5736. if (texture.generateMipMaps) {
  5737. var gl = this._gl;
  5738. gl.bindTexture(gl.TEXTURE_2D, texture);
  5739. gl.generateMipmap(gl.TEXTURE_2D);
  5740. gl.bindTexture(gl.TEXTURE_2D, null);
  5741. }
  5742. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5743. };
  5744. Engine.prototype.flushFramebuffer = function () {
  5745. this._gl.flush();
  5746. };
  5747. Engine.prototype.restoreDefaultFramebuffer = function () {
  5748. this._currentRenderTarget = null;
  5749. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5750. this.setViewport(this._cachedViewport);
  5751. this.wipeCaches();
  5752. };
  5753. // VBOs
  5754. Engine.prototype._resetVertexBufferBinding = function () {
  5755. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5756. this._cachedVertexBuffers = null;
  5757. };
  5758. Engine.prototype.createVertexBuffer = function (vertices) {
  5759. var vbo = this._gl.createBuffer();
  5760. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5761. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5762. this._resetVertexBufferBinding();
  5763. vbo.references = 1;
  5764. return vbo;
  5765. };
  5766. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5767. var vbo = this._gl.createBuffer();
  5768. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5769. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5770. this._resetVertexBufferBinding();
  5771. vbo.references = 1;
  5772. return vbo;
  5773. };
  5774. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5775. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5776. if (offset === undefined) {
  5777. offset = 0;
  5778. }
  5779. if (vertices instanceof Float32Array) {
  5780. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5781. }
  5782. else {
  5783. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5784. }
  5785. this._resetVertexBufferBinding();
  5786. };
  5787. Engine.prototype._resetIndexBufferBinding = function () {
  5788. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5789. this._cachedIndexBuffer = null;
  5790. };
  5791. Engine.prototype.createIndexBuffer = function (indices) {
  5792. var vbo = this._gl.createBuffer();
  5793. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5794. // Check for 32 bits indices
  5795. var arrayBuffer;
  5796. var need32Bits = false;
  5797. if (this._caps.uintIndices) {
  5798. for (var index = 0; index < indices.length; index++) {
  5799. if (indices[index] > 65535) {
  5800. need32Bits = true;
  5801. break;
  5802. }
  5803. }
  5804. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5805. }
  5806. else {
  5807. arrayBuffer = new Uint16Array(indices);
  5808. }
  5809. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5810. this._resetIndexBufferBinding();
  5811. vbo.references = 1;
  5812. vbo.is32Bits = need32Bits;
  5813. return vbo;
  5814. };
  5815. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5816. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5817. this._cachedVertexBuffers = vertexBuffer;
  5818. this._cachedEffectForVertexBuffers = effect;
  5819. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5820. var offset = 0;
  5821. for (var index = 0; index < vertexDeclaration.length; index++) {
  5822. var order = effect.getAttributeLocation(index);
  5823. if (order >= 0) {
  5824. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5825. }
  5826. offset += vertexDeclaration[index] * 4;
  5827. }
  5828. }
  5829. if (this._cachedIndexBuffer !== indexBuffer) {
  5830. this._cachedIndexBuffer = indexBuffer;
  5831. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5832. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5833. }
  5834. };
  5835. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5836. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5837. this._cachedVertexBuffers = vertexBuffers;
  5838. this._cachedEffectForVertexBuffers = effect;
  5839. var attributes = effect.getAttributesNames();
  5840. for (var index = 0; index < attributes.length; index++) {
  5841. var order = effect.getAttributeLocation(index);
  5842. if (order >= 0) {
  5843. var vertexBuffer = vertexBuffers[attributes[index]];
  5844. if (!vertexBuffer) {
  5845. continue;
  5846. }
  5847. var stride = vertexBuffer.getStrideSize();
  5848. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5849. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5850. }
  5851. }
  5852. }
  5853. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5854. this._cachedIndexBuffer = indexBuffer;
  5855. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5856. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5857. }
  5858. };
  5859. Engine.prototype._releaseBuffer = function (buffer) {
  5860. buffer.references--;
  5861. if (buffer.references === 0) {
  5862. this._gl.deleteBuffer(buffer);
  5863. return true;
  5864. }
  5865. return false;
  5866. };
  5867. Engine.prototype.createInstancesBuffer = function (capacity) {
  5868. var buffer = this._gl.createBuffer();
  5869. buffer.capacity = capacity;
  5870. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5871. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5872. return buffer;
  5873. };
  5874. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5875. this._gl.deleteBuffer(buffer);
  5876. };
  5877. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5878. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5879. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5880. for (var index = 0; index < 4; index++) {
  5881. var offsetLocation = offsetLocations[index];
  5882. this._gl.enableVertexAttribArray(offsetLocation);
  5883. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5884. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5885. }
  5886. };
  5887. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5888. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5889. for (var index = 0; index < 4; index++) {
  5890. var offsetLocation = offsetLocations[index];
  5891. this._gl.disableVertexAttribArray(offsetLocation);
  5892. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5893. }
  5894. };
  5895. Engine.prototype.applyStates = function () {
  5896. this._depthCullingState.apply(this._gl);
  5897. this._alphaState.apply(this._gl);
  5898. };
  5899. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5900. // Apply states
  5901. this.applyStates();
  5902. this._drawCalls++;
  5903. // Render
  5904. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5905. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5906. if (instancesCount) {
  5907. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5908. return;
  5909. }
  5910. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5911. };
  5912. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5913. // Apply states
  5914. this.applyStates();
  5915. this._drawCalls++;
  5916. if (instancesCount) {
  5917. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5918. return;
  5919. }
  5920. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5921. };
  5922. // Shaders
  5923. Engine.prototype._releaseEffect = function (effect) {
  5924. if (this._compiledEffects[effect._key]) {
  5925. delete this._compiledEffects[effect._key];
  5926. if (effect.getProgram()) {
  5927. this._gl.deleteProgram(effect.getProgram());
  5928. }
  5929. }
  5930. };
  5931. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5932. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5933. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5934. var name = vertex + "+" + fragment + "@" + defines;
  5935. if (this._compiledEffects[name]) {
  5936. return this._compiledEffects[name];
  5937. }
  5938. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5939. effect._key = name;
  5940. this._compiledEffects[name] = effect;
  5941. return effect;
  5942. };
  5943. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5944. if (uniformsNames === void 0) { uniformsNames = []; }
  5945. if (samplers === void 0) { samplers = []; }
  5946. if (defines === void 0) { defines = ""; }
  5947. return this.createEffect({
  5948. vertex: "particles",
  5949. fragmentElement: fragmentName
  5950. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5951. };
  5952. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5953. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5954. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5955. var shaderProgram = this._gl.createProgram();
  5956. this._gl.attachShader(shaderProgram, vertexShader);
  5957. this._gl.attachShader(shaderProgram, fragmentShader);
  5958. this._gl.linkProgram(shaderProgram);
  5959. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5960. if (!linked) {
  5961. var error = this._gl.getProgramInfoLog(shaderProgram);
  5962. if (error) {
  5963. throw new Error(error);
  5964. }
  5965. }
  5966. this._gl.deleteShader(vertexShader);
  5967. this._gl.deleteShader(fragmentShader);
  5968. return shaderProgram;
  5969. };
  5970. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  5971. var results = [];
  5972. for (var index = 0; index < uniformsNames.length; index++) {
  5973. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  5974. }
  5975. return results;
  5976. };
  5977. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  5978. var results = [];
  5979. for (var index = 0; index < attributesNames.length; index++) {
  5980. try {
  5981. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  5982. }
  5983. catch (e) {
  5984. results.push(-1);
  5985. }
  5986. }
  5987. return results;
  5988. };
  5989. Engine.prototype.enableEffect = function (effect) {
  5990. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  5991. if (effect && effect.onBind) {
  5992. effect.onBind(effect);
  5993. }
  5994. return;
  5995. }
  5996. this._vertexAttribArrays = this._vertexAttribArrays || [];
  5997. // Use program
  5998. this._gl.useProgram(effect.getProgram());
  5999. for (var i in this._vertexAttribArrays) {
  6000. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6001. continue;
  6002. }
  6003. this._vertexAttribArrays[i] = false;
  6004. this._gl.disableVertexAttribArray(i);
  6005. }
  6006. var attributesCount = effect.getAttributesCount();
  6007. for (var index = 0; index < attributesCount; index++) {
  6008. // Attributes
  6009. var order = effect.getAttributeLocation(index);
  6010. if (order >= 0) {
  6011. this._vertexAttribArrays[order] = true;
  6012. this._gl.enableVertexAttribArray(order);
  6013. }
  6014. }
  6015. this._currentEffect = effect;
  6016. if (effect.onBind) {
  6017. effect.onBind(effect);
  6018. }
  6019. };
  6020. Engine.prototype.setArray = function (uniform, array) {
  6021. if (!uniform)
  6022. return;
  6023. this._gl.uniform1fv(uniform, array);
  6024. };
  6025. Engine.prototype.setArray2 = function (uniform, array) {
  6026. if (!uniform || array.length % 2 !== 0)
  6027. return;
  6028. this._gl.uniform2fv(uniform, array);
  6029. };
  6030. Engine.prototype.setArray3 = function (uniform, array) {
  6031. if (!uniform || array.length % 3 !== 0)
  6032. return;
  6033. this._gl.uniform3fv(uniform, array);
  6034. };
  6035. Engine.prototype.setArray4 = function (uniform, array) {
  6036. if (!uniform || array.length % 4 !== 0)
  6037. return;
  6038. this._gl.uniform4fv(uniform, array);
  6039. };
  6040. Engine.prototype.setMatrices = function (uniform, matrices) {
  6041. if (!uniform)
  6042. return;
  6043. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6044. };
  6045. Engine.prototype.setMatrix = function (uniform, matrix) {
  6046. if (!uniform)
  6047. return;
  6048. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6049. };
  6050. Engine.prototype.setFloat = function (uniform, value) {
  6051. if (!uniform)
  6052. return;
  6053. this._gl.uniform1f(uniform, value);
  6054. };
  6055. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6056. if (!uniform)
  6057. return;
  6058. this._gl.uniform2f(uniform, x, y);
  6059. };
  6060. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6061. if (!uniform)
  6062. return;
  6063. this._gl.uniform3f(uniform, x, y, z);
  6064. };
  6065. Engine.prototype.setBool = function (uniform, bool) {
  6066. if (!uniform)
  6067. return;
  6068. this._gl.uniform1i(uniform, bool);
  6069. };
  6070. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6071. if (!uniform)
  6072. return;
  6073. this._gl.uniform4f(uniform, x, y, z, w);
  6074. };
  6075. Engine.prototype.setColor3 = function (uniform, color3) {
  6076. if (!uniform)
  6077. return;
  6078. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6079. };
  6080. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6081. if (!uniform)
  6082. return;
  6083. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6084. };
  6085. // States
  6086. Engine.prototype.setState = function (culling, zOffset, force) {
  6087. if (zOffset === void 0) { zOffset = 0; }
  6088. // Culling
  6089. if (this._depthCullingState.cull !== culling || force) {
  6090. if (culling) {
  6091. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6092. this._depthCullingState.cull = true;
  6093. }
  6094. else {
  6095. this._depthCullingState.cull = false;
  6096. }
  6097. }
  6098. // Z offset
  6099. this._depthCullingState.zOffset = zOffset;
  6100. };
  6101. Engine.prototype.setDepthBuffer = function (enable) {
  6102. this._depthCullingState.depthTest = enable;
  6103. };
  6104. Engine.prototype.getDepthWrite = function () {
  6105. return this._depthCullingState.depthMask;
  6106. };
  6107. Engine.prototype.setDepthWrite = function (enable) {
  6108. this._depthCullingState.depthMask = enable;
  6109. };
  6110. Engine.prototype.setColorWrite = function (enable) {
  6111. this._gl.colorMask(enable, enable, enable, enable);
  6112. };
  6113. Engine.prototype.setAlphaMode = function (mode) {
  6114. switch (mode) {
  6115. case Engine.ALPHA_DISABLE:
  6116. this.setDepthWrite(true);
  6117. this._alphaState.alphaBlend = false;
  6118. break;
  6119. case Engine.ALPHA_COMBINE:
  6120. this.setDepthWrite(false);
  6121. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6122. this._alphaState.alphaBlend = true;
  6123. break;
  6124. case Engine.ALPHA_ADD:
  6125. this.setDepthWrite(false);
  6126. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6127. this._alphaState.alphaBlend = true;
  6128. break;
  6129. }
  6130. this._alphaMode = mode;
  6131. };
  6132. Engine.prototype.getAlphaMode = function () {
  6133. return this._alphaMode;
  6134. };
  6135. Engine.prototype.setAlphaTesting = function (enable) {
  6136. this._alphaTest = enable;
  6137. };
  6138. Engine.prototype.getAlphaTesting = function () {
  6139. return this._alphaTest;
  6140. };
  6141. // Textures
  6142. Engine.prototype.wipeCaches = function () {
  6143. this._activeTexturesCache = [];
  6144. this._currentEffect = null;
  6145. this._depthCullingState.reset();
  6146. this._alphaState.reset();
  6147. this._cachedVertexBuffers = null;
  6148. this._cachedIndexBuffer = null;
  6149. this._cachedEffectForVertexBuffers = null;
  6150. };
  6151. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6152. var gl = this._gl;
  6153. gl.bindTexture(gl.TEXTURE_2D, texture);
  6154. var magFilter = gl.NEAREST;
  6155. var minFilter = gl.NEAREST;
  6156. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6157. magFilter = gl.LINEAR;
  6158. minFilter = gl.LINEAR;
  6159. }
  6160. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6161. magFilter = gl.LINEAR;
  6162. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6163. }
  6164. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6165. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6166. gl.bindTexture(gl.TEXTURE_2D, null);
  6167. texture.samplingMode = samplingMode;
  6168. };
  6169. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6170. var _this = this;
  6171. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6172. if (onLoad === void 0) { onLoad = null; }
  6173. if (onError === void 0) { onError = null; }
  6174. if (buffer === void 0) { buffer = null; }
  6175. var texture = this._gl.createTexture();
  6176. var extension;
  6177. var fromData = false;
  6178. if (url.substr(0, 5) === "data:") {
  6179. fromData = true;
  6180. }
  6181. if (!fromData)
  6182. extension = url.substr(url.length - 4, 4).toLowerCase();
  6183. else {
  6184. var oldUrl = url;
  6185. fromData = oldUrl.split(':');
  6186. url = oldUrl;
  6187. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6188. }
  6189. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6190. var isTGA = (extension === ".tga");
  6191. scene._addPendingData(texture);
  6192. texture.url = url;
  6193. texture.noMipmap = noMipmap;
  6194. texture.references = 1;
  6195. texture.samplingMode = samplingMode;
  6196. this._loadedTexturesCache.push(texture);
  6197. var onerror = function () {
  6198. scene._removePendingData(texture);
  6199. if (onError) {
  6200. onError();
  6201. }
  6202. };
  6203. if (isTGA) {
  6204. var callback = function (arrayBuffer) {
  6205. var data = new Uint8Array(arrayBuffer);
  6206. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6207. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6208. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6209. if (onLoad) {
  6210. onLoad();
  6211. }
  6212. }, samplingMode);
  6213. };
  6214. if (!(fromData instanceof Array))
  6215. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6216. callback(arrayBuffer);
  6217. }, onerror, scene.database, true);
  6218. else
  6219. callback(buffer);
  6220. }
  6221. else if (isDDS) {
  6222. callback = function (data) {
  6223. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6224. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6225. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6226. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6227. if (onLoad) {
  6228. onLoad();
  6229. }
  6230. }, samplingMode);
  6231. };
  6232. if (!(fromData instanceof Array))
  6233. BABYLON.Tools.LoadFile(url, function (data) {
  6234. callback(data);
  6235. }, onerror, scene.database, true);
  6236. else
  6237. callback(buffer);
  6238. }
  6239. else {
  6240. var onload = function (img) {
  6241. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6242. var isPot = (img.width === potWidth && img.height === potHeight);
  6243. if (!isPot) {
  6244. _this._prepareWorkingCanvas();
  6245. _this._workingCanvas.width = potWidth;
  6246. _this._workingCanvas.height = potHeight;
  6247. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6248. _this._workingContext.imageSmoothingEnabled = false;
  6249. _this._workingContext.mozImageSmoothingEnabled = false;
  6250. _this._workingContext.oImageSmoothingEnabled = false;
  6251. _this._workingContext.webkitImageSmoothingEnabled = false;
  6252. _this._workingContext.msImageSmoothingEnabled = false;
  6253. }
  6254. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6255. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6256. _this._workingContext.imageSmoothingEnabled = true;
  6257. _this._workingContext.mozImageSmoothingEnabled = true;
  6258. _this._workingContext.oImageSmoothingEnabled = true;
  6259. _this._workingContext.webkitImageSmoothingEnabled = true;
  6260. _this._workingContext.msImageSmoothingEnabled = true;
  6261. }
  6262. }
  6263. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6264. if (onLoad) {
  6265. onLoad();
  6266. }
  6267. }, samplingMode);
  6268. };
  6269. if (!(fromData instanceof Array))
  6270. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6271. else
  6272. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6273. }
  6274. return texture;
  6275. };
  6276. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6277. var texture = this._gl.createTexture();
  6278. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6279. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6280. // Format
  6281. var internalFormat = this._gl.RGBA;
  6282. switch (format) {
  6283. case Engine.TEXTUREFORMAT_ALPHA:
  6284. internalFormat = this._gl.ALPHA;
  6285. break;
  6286. case Engine.TEXTUREFORMAT_LUMINANCE:
  6287. internalFormat = this._gl.LUMINANCE;
  6288. break;
  6289. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6290. internalFormat = this._gl.LUMINANCE_ALPHA;
  6291. break;
  6292. case Engine.TEXTUREFORMAT_RGB:
  6293. internalFormat = this._gl.RGB;
  6294. break;
  6295. case Engine.TEXTUREFORMAT_RGBA:
  6296. internalFormat = this._gl.RGBA;
  6297. break;
  6298. }
  6299. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6300. if (generateMipMaps) {
  6301. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6302. }
  6303. // Filters
  6304. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6305. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6306. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6307. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6308. this._activeTexturesCache = [];
  6309. texture._baseWidth = width;
  6310. texture._baseHeight = height;
  6311. texture._width = width;
  6312. texture._height = height;
  6313. texture.isReady = true;
  6314. texture.references = 1;
  6315. texture.samplingMode = samplingMode;
  6316. this._loadedTexturesCache.push(texture);
  6317. return texture;
  6318. };
  6319. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  6320. var texture = this._gl.createTexture();
  6321. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6322. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6323. this._activeTexturesCache = [];
  6324. texture._baseWidth = width;
  6325. texture._baseHeight = height;
  6326. texture._width = width;
  6327. texture._height = height;
  6328. texture.isReady = false;
  6329. texture.generateMipMaps = generateMipMaps;
  6330. texture.references = 1;
  6331. texture.samplingMode = samplingMode;
  6332. this.updateTextureSamplingMode(samplingMode, texture);
  6333. this._loadedTexturesCache.push(texture);
  6334. return texture;
  6335. };
  6336. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6337. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6338. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6339. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6340. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6341. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6342. };
  6343. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6344. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6345. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6346. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6347. if (texture.generateMipMaps) {
  6348. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6349. }
  6350. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6351. this._activeTexturesCache = [];
  6352. texture.isReady = true;
  6353. };
  6354. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6355. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6356. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6357. // Scale the video if it is a NPOT using the current working canvas
  6358. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  6359. if (!texture._workingCanvas) {
  6360. texture._workingCanvas = document.createElement("canvas");
  6361. texture._workingContext = texture._workingCanvas.getContext("2d");
  6362. texture._workingCanvas.width = texture._width;
  6363. texture._workingCanvas.height = texture._height;
  6364. }
  6365. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6366. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6367. }
  6368. else {
  6369. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6370. }
  6371. if (texture.generateMipMaps) {
  6372. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6373. }
  6374. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6375. this._activeTexturesCache = [];
  6376. texture.isReady = true;
  6377. };
  6378. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6379. // old version had a "generateMipMaps" arg instead of options.
  6380. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6381. // in the same way, generateDepthBuffer is defaulted to true
  6382. var generateMipMaps = false;
  6383. var generateDepthBuffer = true;
  6384. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6385. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6386. if (options !== undefined) {
  6387. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6388. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6389. type = options.type === undefined ? type : options.type;
  6390. if (options.samplingMode !== undefined) {
  6391. samplingMode = options.samplingMode;
  6392. }
  6393. if (type === Engine.TEXTURETYPE_FLOAT) {
  6394. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6395. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6396. }
  6397. }
  6398. var gl = this._gl;
  6399. var texture = gl.createTexture();
  6400. gl.bindTexture(gl.TEXTURE_2D, texture);
  6401. var width = size.width || size;
  6402. var height = size.height || size;
  6403. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6404. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6405. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6406. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6407. }
  6408. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6409. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6410. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6411. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6412. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6413. var depthBuffer;
  6414. // Create the depth buffer
  6415. if (generateDepthBuffer) {
  6416. depthBuffer = gl.createRenderbuffer();
  6417. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6418. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6419. }
  6420. // Create the framebuffer
  6421. var framebuffer = gl.createFramebuffer();
  6422. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6423. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6424. if (generateDepthBuffer) {
  6425. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6426. }
  6427. // Unbind
  6428. gl.bindTexture(gl.TEXTURE_2D, null);
  6429. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6430. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6431. texture._framebuffer = framebuffer;
  6432. if (generateDepthBuffer) {
  6433. texture._depthBuffer = depthBuffer;
  6434. }
  6435. texture._width = width;
  6436. texture._height = height;
  6437. texture.isReady = true;
  6438. texture.generateMipMaps = generateMipMaps;
  6439. texture.references = 1;
  6440. texture.samplingMode = samplingMode;
  6441. this._activeTexturesCache = [];
  6442. this._loadedTexturesCache.push(texture);
  6443. return texture;
  6444. };
  6445. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6446. var _this = this;
  6447. var gl = this._gl;
  6448. var texture = gl.createTexture();
  6449. texture.isCube = true;
  6450. texture.url = rootUrl;
  6451. texture.references = 1;
  6452. this._loadedTexturesCache.push(texture);
  6453. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6454. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6455. if (isDDS) {
  6456. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6457. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6458. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6459. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6460. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6461. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6462. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6463. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6464. }
  6465. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6466. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6467. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6468. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6469. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6470. _this._activeTexturesCache = [];
  6471. texture._width = info.width;
  6472. texture._height = info.height;
  6473. texture.isReady = true;
  6474. }, null, null, true);
  6475. }
  6476. else {
  6477. cascadeLoad(rootUrl, scene, function (imgs) {
  6478. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6479. var height = width;
  6480. _this._prepareWorkingCanvas();
  6481. _this._workingCanvas.width = width;
  6482. _this._workingCanvas.height = height;
  6483. var faces = [
  6484. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  6485. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  6486. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6487. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  6488. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  6489. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6490. ];
  6491. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6492. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6493. for (var index = 0; index < faces.length; index++) {
  6494. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6495. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6496. }
  6497. if (!noMipmap) {
  6498. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6499. }
  6500. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6501. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6502. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6503. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6504. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6505. _this._activeTexturesCache = [];
  6506. texture._width = width;
  6507. texture._height = height;
  6508. texture.isReady = true;
  6509. }, extensions);
  6510. }
  6511. return texture;
  6512. };
  6513. Engine.prototype._releaseTexture = function (texture) {
  6514. var gl = this._gl;
  6515. if (texture._framebuffer) {
  6516. gl.deleteFramebuffer(texture._framebuffer);
  6517. }
  6518. if (texture._depthBuffer) {
  6519. gl.deleteRenderbuffer(texture._depthBuffer);
  6520. }
  6521. gl.deleteTexture(texture);
  6522. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6523. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6524. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6525. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6526. this._activeTexturesCache[channel] = null;
  6527. }
  6528. var index = this._loadedTexturesCache.indexOf(texture);
  6529. if (index !== -1) {
  6530. this._loadedTexturesCache.splice(index, 1);
  6531. }
  6532. };
  6533. Engine.prototype.bindSamplers = function (effect) {
  6534. this._gl.useProgram(effect.getProgram());
  6535. var samplers = effect.getSamplers();
  6536. for (var index = 0; index < samplers.length; index++) {
  6537. var uniform = effect.getUniform(samplers[index]);
  6538. this._gl.uniform1i(uniform, index);
  6539. }
  6540. this._currentEffect = null;
  6541. };
  6542. Engine.prototype._bindTexture = function (channel, texture) {
  6543. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6544. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6545. this._activeTexturesCache[channel] = null;
  6546. };
  6547. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6548. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6549. };
  6550. Engine.prototype.setTexture = function (channel, texture) {
  6551. if (channel < 0) {
  6552. return;
  6553. }
  6554. // Not ready?
  6555. if (!texture || !texture.isReady()) {
  6556. if (this._activeTexturesCache[channel] != null) {
  6557. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6558. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6559. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6560. this._activeTexturesCache[channel] = null;
  6561. }
  6562. return;
  6563. }
  6564. // Video
  6565. if (texture instanceof BABYLON.VideoTexture) {
  6566. if (texture.update()) {
  6567. this._activeTexturesCache[channel] = null;
  6568. }
  6569. }
  6570. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6571. texture.delayLoad();
  6572. return;
  6573. }
  6574. if (this._activeTexturesCache[channel] === texture) {
  6575. return;
  6576. }
  6577. this._activeTexturesCache[channel] = texture;
  6578. var internalTexture = texture.getInternalTexture();
  6579. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6580. if (internalTexture.isCube) {
  6581. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6582. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6583. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6584. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6585. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6586. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6587. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6588. }
  6589. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6590. }
  6591. else {
  6592. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6593. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6594. internalTexture._cachedWrapU = texture.wrapU;
  6595. switch (texture.wrapU) {
  6596. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6597. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6598. break;
  6599. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6600. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6601. break;
  6602. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6603. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6604. break;
  6605. }
  6606. }
  6607. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6608. internalTexture._cachedWrapV = texture.wrapV;
  6609. switch (texture.wrapV) {
  6610. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6611. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6612. break;
  6613. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6614. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6615. break;
  6616. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6617. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6618. break;
  6619. }
  6620. }
  6621. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6622. }
  6623. };
  6624. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6625. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6626. var value = texture.anisotropicFilteringLevel;
  6627. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6628. value = 1;
  6629. }
  6630. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6631. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6632. texture._cachedAnisotropicFilteringLevel = value;
  6633. }
  6634. };
  6635. Engine.prototype.readPixels = function (x, y, width, height) {
  6636. var data = new Uint8Array(height * width * 4);
  6637. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6638. return data;
  6639. };
  6640. // Dispose
  6641. Engine.prototype.dispose = function () {
  6642. this.hideLoadingUI();
  6643. this.stopRenderLoop();
  6644. while (this.scenes.length) {
  6645. this.scenes[0].dispose();
  6646. }
  6647. // Release audio engine
  6648. Engine.audioEngine.dispose();
  6649. for (var name in this._compiledEffects) {
  6650. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6651. }
  6652. for (var i in this._vertexAttribArrays) {
  6653. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6654. continue;
  6655. }
  6656. this._gl.disableVertexAttribArray(i);
  6657. }
  6658. // Events
  6659. window.removeEventListener("blur", this._onBlur);
  6660. window.removeEventListener("focus", this._onFocus);
  6661. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6662. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6663. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6664. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6665. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6666. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6667. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6668. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6669. };
  6670. // Loading screen
  6671. Engine.prototype.displayLoadingUI = function () {
  6672. var _this = this;
  6673. this._loadingDiv = document.createElement("div");
  6674. this._loadingDiv.style.opacity = "0";
  6675. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6676. // Loading text
  6677. this._loadingTextDiv = document.createElement("div");
  6678. this._loadingTextDiv.style.position = "absolute";
  6679. this._loadingTextDiv.style.left = "0";
  6680. this._loadingTextDiv.style.top = "50%";
  6681. this._loadingTextDiv.style.marginTop = "80px";
  6682. this._loadingTextDiv.style.width = "100%";
  6683. this._loadingTextDiv.style.height = "20px";
  6684. this._loadingTextDiv.style.fontFamily = "Arial";
  6685. this._loadingTextDiv.style.fontSize = "14px";
  6686. this._loadingTextDiv.style.color = "white";
  6687. this._loadingTextDiv.style.textAlign = "center";
  6688. this._loadingTextDiv.innerHTML = "Loading";
  6689. this._loadingDiv.appendChild(this._loadingTextDiv);
  6690. // Loading img
  6691. var imgBack = new Image();
  6692. 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==";
  6693. imgBack.style.position = "absolute";
  6694. imgBack.style.left = "50%";
  6695. imgBack.style.top = "50%";
  6696. imgBack.style.marginLeft = "-50px";
  6697. imgBack.style.marginTop = "-50px";
  6698. imgBack.style.transition = "transform 1.0s ease";
  6699. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6700. var deg = 360;
  6701. var onTransitionEnd = function () {
  6702. deg += 360;
  6703. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6704. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6705. };
  6706. imgBack.addEventListener("transitionend", onTransitionEnd);
  6707. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6708. this._loadingDiv.appendChild(imgBack);
  6709. // front image
  6710. var imgFront = new Image();
  6711. 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=";
  6712. imgFront.style.position = "absolute";
  6713. imgFront.style.left = "50%";
  6714. imgFront.style.top = "50%";
  6715. imgFront.style.marginLeft = "-50px";
  6716. imgFront.style.marginTop = "-50px";
  6717. this._loadingDiv.appendChild(imgFront);
  6718. // Resize
  6719. this._resizeLoadingUI = function () {
  6720. var canvasRect = _this.getRenderingCanvasClientRect();
  6721. _this._loadingDiv.style.position = "absolute";
  6722. _this._loadingDiv.style.left = canvasRect.left + "px";
  6723. _this._loadingDiv.style.top = canvasRect.top + "px";
  6724. _this._loadingDiv.style.width = canvasRect.width + "px";
  6725. _this._loadingDiv.style.height = canvasRect.height + "px";
  6726. };
  6727. this._resizeLoadingUI();
  6728. window.addEventListener("resize", this._resizeLoadingUI);
  6729. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6730. document.body.appendChild(this._loadingDiv);
  6731. setTimeout(function () {
  6732. _this._loadingDiv.style.opacity = "1";
  6733. imgBack.style.transform = "rotateZ(360deg)";
  6734. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6735. }, 0);
  6736. };
  6737. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6738. set: function (text) {
  6739. if (!this._loadingDiv) {
  6740. return;
  6741. }
  6742. this._loadingTextDiv.innerHTML = text;
  6743. },
  6744. enumerable: true,
  6745. configurable: true
  6746. });
  6747. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6748. get: function () {
  6749. return this._loadingDivBackgroundColor;
  6750. },
  6751. set: function (color) {
  6752. this._loadingDivBackgroundColor = color;
  6753. if (!this._loadingDiv) {
  6754. return;
  6755. }
  6756. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6757. },
  6758. enumerable: true,
  6759. configurable: true
  6760. });
  6761. Engine.prototype.hideLoadingUI = function () {
  6762. var _this = this;
  6763. if (!this._loadingDiv) {
  6764. return;
  6765. }
  6766. var onTransitionEnd = function () {
  6767. if (!_this._loadingDiv) {
  6768. return;
  6769. }
  6770. document.body.removeChild(_this._loadingDiv);
  6771. window.removeEventListener("resize", _this._resizeLoadingUI);
  6772. _this._loadingDiv = null;
  6773. };
  6774. this._loadingDiv.style.opacity = "0";
  6775. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6776. };
  6777. // FPS
  6778. Engine.prototype.getFps = function () {
  6779. return this.fps;
  6780. };
  6781. Engine.prototype.getDeltaTime = function () {
  6782. return this.deltaTime;
  6783. };
  6784. Engine.prototype._measureFps = function () {
  6785. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6786. var length = this.previousFramesDuration.length;
  6787. if (length >= 2) {
  6788. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6789. }
  6790. if (length >= this.fpsRange) {
  6791. if (length > this.fpsRange) {
  6792. this.previousFramesDuration.splice(0, 1);
  6793. length = this.previousFramesDuration.length;
  6794. }
  6795. var sum = 0;
  6796. for (var id = 0; id < length - 1; id++) {
  6797. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6798. }
  6799. this.fps = 1000.0 / (sum / (length - 1));
  6800. }
  6801. };
  6802. // Statics
  6803. Engine.isSupported = function () {
  6804. try {
  6805. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6806. if (navigator.isCocoonJS) {
  6807. return true;
  6808. }
  6809. var tempcanvas = document.createElement("canvas");
  6810. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6811. return gl != null && !!window.WebGLRenderingContext;
  6812. }
  6813. catch (e) {
  6814. return false;
  6815. }
  6816. };
  6817. // Const statics
  6818. Engine._ALPHA_DISABLE = 0;
  6819. Engine._ALPHA_ADD = 1;
  6820. Engine._ALPHA_COMBINE = 2;
  6821. Engine._DELAYLOADSTATE_NONE = 0;
  6822. Engine._DELAYLOADSTATE_LOADED = 1;
  6823. Engine._DELAYLOADSTATE_LOADING = 2;
  6824. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6825. Engine._TEXTUREFORMAT_ALPHA = 0;
  6826. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6827. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6828. Engine._TEXTUREFORMAT_RGB = 4;
  6829. Engine._TEXTUREFORMAT_RGBA = 4;
  6830. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6831. Engine._TEXTURETYPE_FLOAT = 1;
  6832. // Updatable statics so stick with vars here
  6833. Engine.Epsilon = 0.001;
  6834. Engine.CollisionsEpsilon = 0.001;
  6835. Engine.CodeRepository = "Babylon/";
  6836. Engine.ShadersRepository = "Babylon/Shaders/";
  6837. return Engine;
  6838. })();
  6839. BABYLON.Engine = Engine;
  6840. })(BABYLON || (BABYLON = {}));
  6841. //# sourceMappingURL=babylon.engine.js.map
  6842. var BABYLON;
  6843. (function (BABYLON) {
  6844. /**
  6845. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6846. */
  6847. var Node = (function () {
  6848. /**
  6849. * @constructor
  6850. * @param {string} name - the name and id to be given to this node
  6851. * @param {BABYLON.Scene} the scene this node will be added to
  6852. */
  6853. function Node(name, scene) {
  6854. this.state = "";
  6855. this.animations = new Array();
  6856. this._childrenFlag = -1;
  6857. this._isEnabled = true;
  6858. this._isReady = true;
  6859. this._currentRenderId = -1;
  6860. this._parentRenderId = -1;
  6861. this.name = name;
  6862. this.id = name;
  6863. this._scene = scene;
  6864. this._initCache();
  6865. }
  6866. Node.prototype.getScene = function () {
  6867. return this._scene;
  6868. };
  6869. Node.prototype.getEngine = function () {
  6870. return this._scene.getEngine();
  6871. };
  6872. // override it in derived class
  6873. Node.prototype.getWorldMatrix = function () {
  6874. return BABYLON.Matrix.Identity();
  6875. };
  6876. // override it in derived class if you add new variables to the cache
  6877. // and call the parent class method
  6878. Node.prototype._initCache = function () {
  6879. this._cache = {};
  6880. this._cache.parent = undefined;
  6881. };
  6882. Node.prototype.updateCache = function (force) {
  6883. if (!force && this.isSynchronized())
  6884. return;
  6885. this._cache.parent = this.parent;
  6886. this._updateCache();
  6887. };
  6888. // override it in derived class if you add new variables to the cache
  6889. // and call the parent class method if !ignoreParentClass
  6890. Node.prototype._updateCache = function (ignoreParentClass) {
  6891. };
  6892. // override it in derived class if you add new variables to the cache
  6893. Node.prototype._isSynchronized = function () {
  6894. return true;
  6895. };
  6896. Node.prototype._markSyncedWithParent = function () {
  6897. this._parentRenderId = this.parent._currentRenderId;
  6898. };
  6899. Node.prototype.isSynchronizedWithParent = function () {
  6900. if (!this.parent) {
  6901. return true;
  6902. }
  6903. if (this._parentRenderId !== this.parent._currentRenderId) {
  6904. return false;
  6905. }
  6906. return this.parent.isSynchronized();
  6907. };
  6908. Node.prototype.isSynchronized = function (updateCache) {
  6909. var check = this.hasNewParent();
  6910. check = check || !this.isSynchronizedWithParent();
  6911. check = check || !this._isSynchronized();
  6912. if (updateCache)
  6913. this.updateCache(true);
  6914. return !check;
  6915. };
  6916. Node.prototype.hasNewParent = function (update) {
  6917. if (this._cache.parent === this.parent)
  6918. return false;
  6919. if (update)
  6920. this._cache.parent = this.parent;
  6921. return true;
  6922. };
  6923. /**
  6924. * Is this node ready to be used/rendered
  6925. * @return {boolean} is it ready
  6926. */
  6927. Node.prototype.isReady = function () {
  6928. return this._isReady;
  6929. };
  6930. /**
  6931. * Is this node enabled.
  6932. * If the node has a parent and is enabled, the parent will be inspected as well.
  6933. * @return {boolean} whether this node (and its parent) is enabled.
  6934. * @see setEnabled
  6935. */
  6936. Node.prototype.isEnabled = function () {
  6937. if (!this._isEnabled) {
  6938. return false;
  6939. }
  6940. if (this.parent) {
  6941. return this.parent.isEnabled();
  6942. }
  6943. return true;
  6944. };
  6945. /**
  6946. * Set the enabled state of this node.
  6947. * @param {boolean} value - the new enabled state
  6948. * @see isEnabled
  6949. */
  6950. Node.prototype.setEnabled = function (value) {
  6951. this._isEnabled = value;
  6952. };
  6953. /**
  6954. * Is this node a descendant of the given node.
  6955. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  6956. * @param {BABYLON.Node} ancestor - The parent node to inspect
  6957. * @see parent
  6958. */
  6959. Node.prototype.isDescendantOf = function (ancestor) {
  6960. if (this.parent) {
  6961. if (this.parent === ancestor) {
  6962. return true;
  6963. }
  6964. return this.parent.isDescendantOf(ancestor);
  6965. }
  6966. return false;
  6967. };
  6968. Node.prototype._getDescendants = function (list, results) {
  6969. for (var index = 0; index < list.length; index++) {
  6970. var item = list[index];
  6971. if (item.isDescendantOf(this)) {
  6972. results.push(item);
  6973. }
  6974. }
  6975. };
  6976. /**
  6977. * Will return all nodes that have this node as parent.
  6978. * @return {BABYLON.Node[]} all children nodes of all types.
  6979. */
  6980. Node.prototype.getDescendants = function () {
  6981. var results = [];
  6982. this._getDescendants(this._scene.meshes, results);
  6983. this._getDescendants(this._scene.lights, results);
  6984. this._getDescendants(this._scene.cameras, results);
  6985. return results;
  6986. };
  6987. Node.prototype._setReady = function (state) {
  6988. if (state == this._isReady) {
  6989. return;
  6990. }
  6991. if (!state) {
  6992. this._isReady = false;
  6993. return;
  6994. }
  6995. this._isReady = true;
  6996. if (this.onReady) {
  6997. this.onReady(this);
  6998. }
  6999. };
  7000. return Node;
  7001. })();
  7002. BABYLON.Node = Node;
  7003. })(BABYLON || (BABYLON = {}));
  7004. //# sourceMappingURL=babylon.node.js.map
  7005. var BABYLON;
  7006. (function (BABYLON) {
  7007. var FilesInput = (function () {
  7008. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7009. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7010. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7011. this._engine = p_engine;
  7012. this._canvas = p_canvas;
  7013. this._currentScene = p_scene;
  7014. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7015. this._progressCallback = p_progressCallback;
  7016. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7017. this._textureLoadingCallback = p_textureLoadingCallback;
  7018. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7019. }
  7020. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7021. var _this = this;
  7022. if (p_elementToMonitor) {
  7023. this._elementToMonitor = p_elementToMonitor;
  7024. this._elementToMonitor.addEventListener("dragenter", function (e) {
  7025. _this.drag(e);
  7026. }, false);
  7027. this._elementToMonitor.addEventListener("dragover", function (e) {
  7028. _this.drag(e);
  7029. }, false);
  7030. this._elementToMonitor.addEventListener("drop", function (e) {
  7031. _this.drop(e);
  7032. }, false);
  7033. }
  7034. };
  7035. FilesInput.prototype.renderFunction = function () {
  7036. if (this._additionnalRenderLoopLogicCallback) {
  7037. this._additionnalRenderLoopLogicCallback();
  7038. }
  7039. if (this._currentScene) {
  7040. if (this._textureLoadingCallback) {
  7041. var remaining = this._currentScene.getWaitingItemsCount();
  7042. if (remaining > 0) {
  7043. this._textureLoadingCallback(remaining);
  7044. }
  7045. }
  7046. this._currentScene.render();
  7047. }
  7048. };
  7049. FilesInput.prototype.drag = function (e) {
  7050. e.stopPropagation();
  7051. e.preventDefault();
  7052. };
  7053. FilesInput.prototype.drop = function (eventDrop) {
  7054. eventDrop.stopPropagation();
  7055. eventDrop.preventDefault();
  7056. this.loadFiles(eventDrop);
  7057. };
  7058. FilesInput.prototype.loadFiles = function (event) {
  7059. if (this._startingProcessingFilesCallback)
  7060. this._startingProcessingFilesCallback();
  7061. // Handling data transfer via drag'n'drop
  7062. if (event && event.dataTransfer && event.dataTransfer.files) {
  7063. this._filesToLoad = event.dataTransfer.files;
  7064. }
  7065. // Handling files from input files
  7066. if (event && event.target && event.target.files) {
  7067. this._filesToLoad = event.target.files;
  7068. }
  7069. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7070. for (var i = 0; i < this._filesToLoad.length; i++) {
  7071. switch (this._filesToLoad[i].type) {
  7072. case "image/jpeg":
  7073. case "image/png":
  7074. case "image/bmp":
  7075. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7076. break;
  7077. case "image/targa":
  7078. case "image/vnd.ms-dds":
  7079. case "audio/wav":
  7080. case "audio/x-wav":
  7081. case "audio/mp3":
  7082. case "audio/mpeg":
  7083. case "audio/mpeg3":
  7084. case "audio/x-mpeg-3":
  7085. case "audio/ogg":
  7086. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7087. break;
  7088. default:
  7089. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1 && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  7090. this._sceneFileToLoad = this._filesToLoad[i];
  7091. }
  7092. break;
  7093. }
  7094. }
  7095. this.reload();
  7096. }
  7097. };
  7098. FilesInput.prototype.reload = function () {
  7099. var _this = this;
  7100. var that = this;
  7101. // If a ".babylon" file has been provided
  7102. if (this._sceneFileToLoad) {
  7103. if (this._currentScene) {
  7104. this._engine.stopRenderLoop();
  7105. this._currentScene.dispose();
  7106. }
  7107. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7108. that._currentScene = newScene;
  7109. // Wait for textures and shaders to be ready
  7110. that._currentScene.executeWhenReady(function () {
  7111. // Attach camera to canvas inputs
  7112. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7113. that._currentScene.createDefaultCameraOrLight();
  7114. }
  7115. that._currentScene.activeCamera.attachControl(that._canvas);
  7116. if (that._sceneLoadedCallback) {
  7117. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7118. }
  7119. that._engine.runRenderLoop(function () {
  7120. that.renderFunction();
  7121. });
  7122. });
  7123. }, function (progress) {
  7124. if (_this._progressCallback) {
  7125. _this._progressCallback(progress);
  7126. }
  7127. });
  7128. }
  7129. else {
  7130. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7131. }
  7132. };
  7133. FilesInput.FilesTextures = new Array();
  7134. FilesInput.FilesToLoad = new Array();
  7135. return FilesInput;
  7136. })();
  7137. BABYLON.FilesInput = FilesInput;
  7138. })(BABYLON || (BABYLON = {}));
  7139. //# sourceMappingURL=babylon.filesInput.js.map
  7140. var BABYLON;
  7141. (function (BABYLON) {
  7142. var IntersectionInfo = (function () {
  7143. function IntersectionInfo(bu, bv, distance) {
  7144. this.bu = bu;
  7145. this.bv = bv;
  7146. this.distance = distance;
  7147. this.faceId = 0;
  7148. this.subMeshId = 0;
  7149. }
  7150. return IntersectionInfo;
  7151. })();
  7152. BABYLON.IntersectionInfo = IntersectionInfo;
  7153. var PickingInfo = (function () {
  7154. function PickingInfo() {
  7155. this.hit = false;
  7156. this.distance = 0;
  7157. this.pickedPoint = null;
  7158. this.pickedMesh = null;
  7159. this.bu = 0;
  7160. this.bv = 0;
  7161. this.faceId = -1;
  7162. this.subMeshId = 0;
  7163. }
  7164. // Methods
  7165. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  7166. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7167. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7168. return null;
  7169. }
  7170. var indices = this.pickedMesh.getIndices();
  7171. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7172. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7173. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7174. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7175. normal0 = normal0.scale(this.bu);
  7176. normal1 = normal1.scale(this.bv);
  7177. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7178. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7179. if (useWorldCoordinates) {
  7180. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7181. }
  7182. return result;
  7183. };
  7184. PickingInfo.prototype.getTextureCoordinates = function () {
  7185. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7186. return null;
  7187. }
  7188. var indices = this.pickedMesh.getIndices();
  7189. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7190. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7191. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7192. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7193. uv0 = uv0.scale(this.bu);
  7194. uv1 = uv1.scale(this.bv);
  7195. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  7196. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7197. };
  7198. return PickingInfo;
  7199. })();
  7200. BABYLON.PickingInfo = PickingInfo;
  7201. })(BABYLON || (BABYLON = {}));
  7202. //# sourceMappingURL=babylon.pickingInfo.js.map
  7203. var BABYLON;
  7204. (function (BABYLON) {
  7205. var BoundingSphere = (function () {
  7206. function BoundingSphere(minimum, maximum) {
  7207. this.minimum = minimum;
  7208. this.maximum = maximum;
  7209. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7210. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7211. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7212. this.radius = distance * 0.5;
  7213. this.centerWorld = BABYLON.Vector3.Zero();
  7214. this._update(BABYLON.Matrix.Identity());
  7215. }
  7216. // Methods
  7217. BoundingSphere.prototype._update = function (world) {
  7218. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7219. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7220. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7221. };
  7222. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7223. for (var i = 0; i < 6; i++) {
  7224. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7225. return false;
  7226. }
  7227. return true;
  7228. };
  7229. BoundingSphere.prototype.intersectsPoint = function (point) {
  7230. var x = this.centerWorld.x - point.x;
  7231. var y = this.centerWorld.y - point.y;
  7232. var z = this.centerWorld.z - point.z;
  7233. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7234. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7235. return false;
  7236. return true;
  7237. };
  7238. // Statics
  7239. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7240. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7241. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7242. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7243. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7244. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7245. return false;
  7246. return true;
  7247. };
  7248. return BoundingSphere;
  7249. })();
  7250. BABYLON.BoundingSphere = BoundingSphere;
  7251. })(BABYLON || (BABYLON = {}));
  7252. //# sourceMappingURL=babylon.boundingSphere.js.map
  7253. var BABYLON;
  7254. (function (BABYLON) {
  7255. var BoundingBox = (function () {
  7256. function BoundingBox(minimum, maximum) {
  7257. this.minimum = minimum;
  7258. this.maximum = maximum;
  7259. this.vectors = new Array();
  7260. this.vectorsWorld = new Array();
  7261. // Bounding vectors
  7262. this.vectors.push(this.minimum.clone());
  7263. this.vectors.push(this.maximum.clone());
  7264. this.vectors.push(this.minimum.clone());
  7265. this.vectors[2].x = this.maximum.x;
  7266. this.vectors.push(this.minimum.clone());
  7267. this.vectors[3].y = this.maximum.y;
  7268. this.vectors.push(this.minimum.clone());
  7269. this.vectors[4].z = this.maximum.z;
  7270. this.vectors.push(this.maximum.clone());
  7271. this.vectors[5].z = this.minimum.z;
  7272. this.vectors.push(this.maximum.clone());
  7273. this.vectors[6].x = this.minimum.x;
  7274. this.vectors.push(this.maximum.clone());
  7275. this.vectors[7].y = this.minimum.y;
  7276. // OBB
  7277. this.center = this.maximum.add(this.minimum).scale(0.5);
  7278. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7279. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7280. for (var index = 0; index < this.vectors.length; index++) {
  7281. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7282. }
  7283. this.minimumWorld = BABYLON.Vector3.Zero();
  7284. this.maximumWorld = BABYLON.Vector3.Zero();
  7285. this._update(BABYLON.Matrix.Identity());
  7286. }
  7287. // Methods
  7288. BoundingBox.prototype.getWorldMatrix = function () {
  7289. return this._worldMatrix;
  7290. };
  7291. BoundingBox.prototype._update = function (world) {
  7292. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7293. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7294. for (var index = 0; index < this.vectors.length; index++) {
  7295. var v = this.vectorsWorld[index];
  7296. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7297. if (v.x < this.minimumWorld.x)
  7298. this.minimumWorld.x = v.x;
  7299. if (v.y < this.minimumWorld.y)
  7300. this.minimumWorld.y = v.y;
  7301. if (v.z < this.minimumWorld.z)
  7302. this.minimumWorld.z = v.z;
  7303. if (v.x > this.maximumWorld.x)
  7304. this.maximumWorld.x = v.x;
  7305. if (v.y > this.maximumWorld.y)
  7306. this.maximumWorld.y = v.y;
  7307. if (v.z > this.maximumWorld.z)
  7308. this.maximumWorld.z = v.z;
  7309. }
  7310. // OBB
  7311. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7312. this.center.scaleInPlace(0.5);
  7313. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7314. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7315. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7316. this._worldMatrix = world;
  7317. };
  7318. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7319. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7320. };
  7321. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7322. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7323. };
  7324. BoundingBox.prototype.intersectsPoint = function (point) {
  7325. var delta = -BABYLON.Engine.Epsilon;
  7326. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7327. return false;
  7328. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7329. return false;
  7330. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7331. return false;
  7332. return true;
  7333. };
  7334. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7335. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7336. };
  7337. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7338. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7339. return false;
  7340. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7341. return false;
  7342. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7343. return false;
  7344. return true;
  7345. };
  7346. // Statics
  7347. BoundingBox.Intersects = function (box0, box1) {
  7348. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7349. return false;
  7350. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7351. return false;
  7352. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7353. return false;
  7354. return true;
  7355. };
  7356. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7357. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7358. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7359. return (num <= (sphereRadius * sphereRadius));
  7360. };
  7361. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7362. for (var p = 0; p < 6; p++) {
  7363. for (var i = 0; i < 8; i++) {
  7364. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7365. return false;
  7366. }
  7367. }
  7368. }
  7369. return true;
  7370. };
  7371. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7372. for (var p = 0; p < 6; p++) {
  7373. var inCount = 8;
  7374. for (var i = 0; i < 8; i++) {
  7375. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7376. --inCount;
  7377. }
  7378. else {
  7379. break;
  7380. }
  7381. }
  7382. if (inCount === 0)
  7383. return false;
  7384. }
  7385. return true;
  7386. };
  7387. return BoundingBox;
  7388. })();
  7389. BABYLON.BoundingBox = BoundingBox;
  7390. })(BABYLON || (BABYLON = {}));
  7391. //# sourceMappingURL=babylon.boundingBox.js.map
  7392. var BABYLON;
  7393. (function (BABYLON) {
  7394. var computeBoxExtents = function (axis, box) {
  7395. var p = BABYLON.Vector3.Dot(box.center, axis);
  7396. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7397. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7398. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7399. var r = r0 + r1 + r2;
  7400. return {
  7401. min: p - r,
  7402. max: p + r
  7403. };
  7404. };
  7405. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7406. var axisOverlap = function (axis, box0, box1) {
  7407. var result0 = computeBoxExtents(axis, box0);
  7408. var result1 = computeBoxExtents(axis, box1);
  7409. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7410. };
  7411. var BoundingInfo = (function () {
  7412. function BoundingInfo(minimum, maximum) {
  7413. this.minimum = minimum;
  7414. this.maximum = maximum;
  7415. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7416. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7417. }
  7418. // Methods
  7419. BoundingInfo.prototype._update = function (world) {
  7420. this.boundingBox._update(world);
  7421. this.boundingSphere._update(world);
  7422. };
  7423. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7424. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7425. return false;
  7426. return this.boundingBox.isInFrustum(frustumPlanes);
  7427. };
  7428. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7429. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7430. };
  7431. BoundingInfo.prototype._checkCollision = function (collider) {
  7432. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7433. };
  7434. BoundingInfo.prototype.intersectsPoint = function (point) {
  7435. if (!this.boundingSphere.centerWorld) {
  7436. return false;
  7437. }
  7438. if (!this.boundingSphere.intersectsPoint(point)) {
  7439. return false;
  7440. }
  7441. if (!this.boundingBox.intersectsPoint(point)) {
  7442. return false;
  7443. }
  7444. return true;
  7445. };
  7446. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7447. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7448. return false;
  7449. }
  7450. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7451. return false;
  7452. }
  7453. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7454. return false;
  7455. }
  7456. if (!precise) {
  7457. return true;
  7458. }
  7459. var box0 = this.boundingBox;
  7460. var box1 = boundingInfo.boundingBox;
  7461. if (!axisOverlap(box0.directions[0], box0, box1))
  7462. return false;
  7463. if (!axisOverlap(box0.directions[1], box0, box1))
  7464. return false;
  7465. if (!axisOverlap(box0.directions[2], box0, box1))
  7466. return false;
  7467. if (!axisOverlap(box1.directions[0], box0, box1))
  7468. return false;
  7469. if (!axisOverlap(box1.directions[1], box0, box1))
  7470. return false;
  7471. if (!axisOverlap(box1.directions[2], box0, box1))
  7472. return false;
  7473. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7474. return false;
  7475. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7476. return false;
  7477. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7478. return false;
  7479. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7480. return false;
  7481. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7482. return false;
  7483. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7484. return false;
  7485. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7486. return false;
  7487. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7488. return false;
  7489. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7490. return false;
  7491. return true;
  7492. };
  7493. return BoundingInfo;
  7494. })();
  7495. BABYLON.BoundingInfo = BoundingInfo;
  7496. })(BABYLON || (BABYLON = {}));
  7497. //# sourceMappingURL=babylon.boundingInfo.js.map
  7498. var __extends = this.__extends || function (d, b) {
  7499. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  7500. function __() { this.constructor = d; }
  7501. __.prototype = b.prototype;
  7502. d.prototype = new __();
  7503. };
  7504. var BABYLON;
  7505. (function (BABYLON) {
  7506. var AbstractMesh = (function (_super) {
  7507. __extends(AbstractMesh, _super);
  7508. function AbstractMesh(name, scene) {
  7509. var _this = this;
  7510. _super.call(this, name, scene);
  7511. // Properties
  7512. this.definedFacingForward = true; // orientation for POV movement & rotation
  7513. this.position = new BABYLON.Vector3(0, 0, 0);
  7514. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7515. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7516. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7517. this.visibility = 1.0;
  7518. this.alphaIndex = Number.MAX_VALUE;
  7519. this.infiniteDistance = false;
  7520. this.isVisible = true;
  7521. this.isPickable = true;
  7522. this.showBoundingBox = false;
  7523. this.showSubMeshesBoundingBox = false;
  7524. this.onDispose = null;
  7525. this.checkCollisions = false;
  7526. this.isBlocker = false;
  7527. this.renderingGroupId = 0;
  7528. this.receiveShadows = false;
  7529. this.renderOutline = false;
  7530. this.outlineColor = BABYLON.Color3.Red();
  7531. this.outlineWidth = 0.02;
  7532. this.renderOverlay = false;
  7533. this.overlayColor = BABYLON.Color3.Red();
  7534. this.overlayAlpha = 0.5;
  7535. this.hasVertexAlpha = false;
  7536. this.useVertexColors = true;
  7537. this.applyFog = true;
  7538. this.useOctreeForRenderingSelection = true;
  7539. this.useOctreeForPicking = true;
  7540. this.useOctreeForCollisions = true;
  7541. this.layerMask = 0x0FFFFFFF;
  7542. this.alwaysSelectAsActiveMesh = false;
  7543. // Physics
  7544. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7545. // Collisions
  7546. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7547. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7548. this._collider = new BABYLON.Collider();
  7549. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7550. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7551. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7552. // Cache
  7553. this._localScaling = BABYLON.Matrix.Zero();
  7554. this._localRotation = BABYLON.Matrix.Zero();
  7555. this._localTranslation = BABYLON.Matrix.Zero();
  7556. this._localBillboard = BABYLON.Matrix.Zero();
  7557. this._localPivotScaling = BABYLON.Matrix.Zero();
  7558. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7559. this._localWorld = BABYLON.Matrix.Zero();
  7560. this._worldMatrix = BABYLON.Matrix.Zero();
  7561. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7562. this._absolutePosition = BABYLON.Vector3.Zero();
  7563. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7564. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7565. this._isDirty = false;
  7566. this._pivotMatrix = BABYLON.Matrix.Identity();
  7567. this._isDisposed = false;
  7568. this._renderId = 0;
  7569. this._intersectionsInProgress = new Array();
  7570. this._onAfterWorldMatrixUpdate = new Array();
  7571. this._isWorldMatrixFrozen = false;
  7572. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7573. if (collidedMesh === void 0) { collidedMesh = null; }
  7574. //TODO move this to the collision coordinator!
  7575. if (_this.getScene().workerCollisions)
  7576. newPosition.multiplyInPlace(_this._collider.radius);
  7577. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7578. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7579. _this.position.addInPlace(_this._diffPositionForCollisions);
  7580. }
  7581. };
  7582. scene.addMesh(this);
  7583. }
  7584. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7585. get: function () {
  7586. return AbstractMesh._BILLBOARDMODE_NONE;
  7587. },
  7588. enumerable: true,
  7589. configurable: true
  7590. });
  7591. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7592. get: function () {
  7593. return AbstractMesh._BILLBOARDMODE_X;
  7594. },
  7595. enumerable: true,
  7596. configurable: true
  7597. });
  7598. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7599. get: function () {
  7600. return AbstractMesh._BILLBOARDMODE_Y;
  7601. },
  7602. enumerable: true,
  7603. configurable: true
  7604. });
  7605. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7606. get: function () {
  7607. return AbstractMesh._BILLBOARDMODE_Z;
  7608. },
  7609. enumerable: true,
  7610. configurable: true
  7611. });
  7612. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7613. get: function () {
  7614. return AbstractMesh._BILLBOARDMODE_ALL;
  7615. },
  7616. enumerable: true,
  7617. configurable: true
  7618. });
  7619. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7620. // Methods
  7621. get: function () {
  7622. return false;
  7623. },
  7624. enumerable: true,
  7625. configurable: true
  7626. });
  7627. AbstractMesh.prototype.getLOD = function (camera) {
  7628. return this;
  7629. };
  7630. AbstractMesh.prototype.getTotalVertices = function () {
  7631. return 0;
  7632. };
  7633. AbstractMesh.prototype.getIndices = function () {
  7634. return null;
  7635. };
  7636. AbstractMesh.prototype.getVerticesData = function (kind) {
  7637. return null;
  7638. };
  7639. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7640. return false;
  7641. };
  7642. AbstractMesh.prototype.getBoundingInfo = function () {
  7643. if (this._masterMesh) {
  7644. return this._masterMesh.getBoundingInfo();
  7645. }
  7646. if (!this._boundingInfo) {
  7647. this._updateBoundingInfo();
  7648. }
  7649. return this._boundingInfo;
  7650. };
  7651. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7652. get: function () {
  7653. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7654. },
  7655. enumerable: true,
  7656. configurable: true
  7657. });
  7658. AbstractMesh.prototype._preActivate = function () {
  7659. };
  7660. AbstractMesh.prototype._activate = function (renderId) {
  7661. this._renderId = renderId;
  7662. };
  7663. AbstractMesh.prototype.getWorldMatrix = function () {
  7664. if (this._masterMesh) {
  7665. return this._masterMesh.getWorldMatrix();
  7666. }
  7667. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7668. this.computeWorldMatrix();
  7669. }
  7670. return this._worldMatrix;
  7671. };
  7672. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7673. get: function () {
  7674. return this._worldMatrix;
  7675. },
  7676. enumerable: true,
  7677. configurable: true
  7678. });
  7679. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7680. get: function () {
  7681. return this._absolutePosition;
  7682. },
  7683. enumerable: true,
  7684. configurable: true
  7685. });
  7686. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7687. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7688. this.computeWorldMatrix(true);
  7689. this._isWorldMatrixFrozen = true;
  7690. };
  7691. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7692. this._isWorldMatrixFrozen = false;
  7693. this.computeWorldMatrix(true);
  7694. };
  7695. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7696. get: function () {
  7697. return this._isWorldMatrixFrozen;
  7698. },
  7699. enumerable: true,
  7700. configurable: true
  7701. });
  7702. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7703. if (!this.rotationQuaternion) {
  7704. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7705. this.rotation = BABYLON.Vector3.Zero();
  7706. }
  7707. if (!space || space === 0 /* LOCAL */) {
  7708. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7709. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7710. }
  7711. else {
  7712. if (this.parent) {
  7713. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7714. invertParentWorldMatrix.invert();
  7715. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7716. }
  7717. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7718. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7719. }
  7720. };
  7721. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7722. var displacementVector = axis.scale(distance);
  7723. if (!space || space === 0 /* LOCAL */) {
  7724. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7725. this.setPositionWithLocalVector(tempV3);
  7726. }
  7727. else {
  7728. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7729. }
  7730. };
  7731. AbstractMesh.prototype.getAbsolutePosition = function () {
  7732. this.computeWorldMatrix();
  7733. return this._absolutePosition;
  7734. };
  7735. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7736. if (!absolutePosition) {
  7737. return;
  7738. }
  7739. var absolutePositionX;
  7740. var absolutePositionY;
  7741. var absolutePositionZ;
  7742. if (absolutePosition.x === undefined) {
  7743. if (arguments.length < 3) {
  7744. return;
  7745. }
  7746. absolutePositionX = arguments[0];
  7747. absolutePositionY = arguments[1];
  7748. absolutePositionZ = arguments[2];
  7749. }
  7750. else {
  7751. absolutePositionX = absolutePosition.x;
  7752. absolutePositionY = absolutePosition.y;
  7753. absolutePositionZ = absolutePosition.z;
  7754. }
  7755. if (this.parent) {
  7756. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7757. invertParentWorldMatrix.invert();
  7758. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7759. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7760. }
  7761. else {
  7762. this.position.x = absolutePositionX;
  7763. this.position.y = absolutePositionY;
  7764. this.position.z = absolutePositionZ;
  7765. }
  7766. };
  7767. // ================================== Point of View Movement =================================
  7768. /**
  7769. * Perform relative position change from the point of view of behind the front of the mesh.
  7770. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7771. * Supports definition of mesh facing forward or backward.
  7772. * @param {number} amountRight
  7773. * @param {number} amountUp
  7774. * @param {number} amountForward
  7775. */
  7776. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7777. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7778. };
  7779. /**
  7780. * Calculate relative position change from the point of view of behind the front of the mesh.
  7781. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7782. * Supports definition of mesh facing forward or backward.
  7783. * @param {number} amountRight
  7784. * @param {number} amountUp
  7785. * @param {number} amountForward
  7786. */
  7787. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7788. var rotMatrix = new BABYLON.Matrix();
  7789. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7790. rotQuaternion.toRotationMatrix(rotMatrix);
  7791. var translationDelta = BABYLON.Vector3.Zero();
  7792. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7793. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7794. return translationDelta;
  7795. };
  7796. // ================================== Point of View Rotation =================================
  7797. /**
  7798. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7799. * Supports definition of mesh facing forward or backward.
  7800. * @param {number} flipBack
  7801. * @param {number} twirlClockwise
  7802. * @param {number} tiltRight
  7803. */
  7804. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7805. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7806. };
  7807. /**
  7808. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7809. * Supports definition of mesh facing forward or backward.
  7810. * @param {number} flipBack
  7811. * @param {number} twirlClockwise
  7812. * @param {number} tiltRight
  7813. */
  7814. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7815. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7816. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7817. };
  7818. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7819. this._pivotMatrix = matrix;
  7820. this._cache.pivotMatrixUpdated = true;
  7821. };
  7822. AbstractMesh.prototype.getPivotMatrix = function () {
  7823. return this._pivotMatrix;
  7824. };
  7825. AbstractMesh.prototype._isSynchronized = function () {
  7826. if (this._isDirty) {
  7827. return false;
  7828. }
  7829. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7830. return false;
  7831. if (this._cache.pivotMatrixUpdated) {
  7832. return false;
  7833. }
  7834. if (this.infiniteDistance) {
  7835. return false;
  7836. }
  7837. if (!this._cache.position.equals(this.position))
  7838. return false;
  7839. if (this.rotationQuaternion) {
  7840. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7841. return false;
  7842. }
  7843. else {
  7844. if (!this._cache.rotation.equals(this.rotation))
  7845. return false;
  7846. }
  7847. if (!this._cache.scaling.equals(this.scaling))
  7848. return false;
  7849. return true;
  7850. };
  7851. AbstractMesh.prototype._initCache = function () {
  7852. _super.prototype._initCache.call(this);
  7853. this._cache.localMatrixUpdated = false;
  7854. this._cache.position = BABYLON.Vector3.Zero();
  7855. this._cache.scaling = BABYLON.Vector3.Zero();
  7856. this._cache.rotation = BABYLON.Vector3.Zero();
  7857. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7858. };
  7859. AbstractMesh.prototype.markAsDirty = function (property) {
  7860. if (property === "rotation") {
  7861. this.rotationQuaternion = null;
  7862. }
  7863. this._currentRenderId = Number.MAX_VALUE;
  7864. this._isDirty = true;
  7865. };
  7866. AbstractMesh.prototype._updateBoundingInfo = function () {
  7867. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7868. this._boundingInfo._update(this.worldMatrixFromCache);
  7869. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7870. };
  7871. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7872. if (!this.subMeshes) {
  7873. return;
  7874. }
  7875. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7876. var subMesh = this.subMeshes[subIndex];
  7877. subMesh.updateBoundingInfo(matrix);
  7878. }
  7879. };
  7880. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7881. if (this._isWorldMatrixFrozen) {
  7882. return this._worldMatrix;
  7883. }
  7884. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7885. return this._worldMatrix;
  7886. }
  7887. this._cache.position.copyFrom(this.position);
  7888. this._cache.scaling.copyFrom(this.scaling);
  7889. this._cache.pivotMatrixUpdated = false;
  7890. this._currentRenderId = this.getScene().getRenderId();
  7891. this._isDirty = false;
  7892. // Scaling
  7893. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7894. // Rotation
  7895. if (this.rotationQuaternion) {
  7896. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7897. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7898. }
  7899. else {
  7900. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7901. this._cache.rotation.copyFrom(this.rotation);
  7902. }
  7903. // Translation
  7904. if (this.infiniteDistance && !this.parent) {
  7905. var camera = this.getScene().activeCamera;
  7906. var cameraWorldMatrix = camera.getWorldMatrix();
  7907. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7908. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7909. }
  7910. else {
  7911. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7912. }
  7913. // Composing transformations
  7914. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7915. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7916. // Billboarding
  7917. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7918. var localPosition = this.position.clone();
  7919. var zero = this.getScene().activeCamera.globalPosition.clone();
  7920. if (this.parent && this.parent.position) {
  7921. localPosition.addInPlace(this.parent.position);
  7922. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7923. }
  7924. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  7925. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7926. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7927. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7928. zero.y = localPosition.y + 0.001;
  7929. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7930. zero.z = localPosition.z + 0.001;
  7931. }
  7932. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7933. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7934. this._localBillboard.invert();
  7935. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7936. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7937. }
  7938. // Local world
  7939. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7940. // Parent
  7941. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7942. this._markSyncedWithParent();
  7943. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7944. }
  7945. else {
  7946. this._worldMatrix.copyFrom(this._localWorld);
  7947. }
  7948. // Bounding info
  7949. this._updateBoundingInfo();
  7950. // Absolute position
  7951. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7952. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7953. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7954. }
  7955. return this._worldMatrix;
  7956. };
  7957. /**
  7958. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7959. * @param func: callback function to add
  7960. */
  7961. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  7962. this._onAfterWorldMatrixUpdate.push(func);
  7963. };
  7964. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  7965. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  7966. if (index > -1) {
  7967. this._onAfterWorldMatrixUpdate.splice(index, 1);
  7968. }
  7969. };
  7970. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  7971. this.computeWorldMatrix();
  7972. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  7973. };
  7974. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  7975. this.computeWorldMatrix();
  7976. var invLocalWorldMatrix = this._localWorld.clone();
  7977. invLocalWorldMatrix.invert();
  7978. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  7979. };
  7980. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  7981. this.computeWorldMatrix(true);
  7982. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  7983. };
  7984. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  7985. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  7986. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  7987. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  7988. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  7989. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  7990. /// <returns>Mesh oriented towards targetMesh</returns>
  7991. yawCor = yawCor || 0; // default to zero if undefined
  7992. pitchCor = pitchCor || 0;
  7993. rollCor = rollCor || 0;
  7994. var dv = targetPoint.subtract(this.position);
  7995. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  7996. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  7997. var pitch = Math.atan2(dv.y, len);
  7998. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  7999. };
  8000. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8001. return this._boundingInfo.isInFrustum(frustumPlanes);
  8002. };
  8003. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8004. if (!camera) {
  8005. camera = this.getScene().activeCamera;
  8006. }
  8007. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8008. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8009. return false;
  8010. }
  8011. return true;
  8012. };
  8013. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8014. if (!this._boundingInfo || !mesh._boundingInfo) {
  8015. return false;
  8016. }
  8017. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8018. };
  8019. AbstractMesh.prototype.intersectsPoint = function (point) {
  8020. if (!this._boundingInfo) {
  8021. return false;
  8022. }
  8023. return this._boundingInfo.intersectsPoint(point);
  8024. };
  8025. // Physics
  8026. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8027. var physicsEngine = this.getScene().getPhysicsEngine();
  8028. if (!physicsEngine) {
  8029. return;
  8030. }
  8031. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8032. if (impostor.impostor) {
  8033. // Old API
  8034. options = impostor;
  8035. impostor = impostor.impostor;
  8036. }
  8037. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8038. physicsEngine._unregisterMesh(this);
  8039. return;
  8040. }
  8041. if (!options) {
  8042. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8043. }
  8044. else {
  8045. if (!options.mass && options.mass !== 0)
  8046. options.mass = 0;
  8047. if (!options.friction && options.friction !== 0)
  8048. options.friction = 0.2;
  8049. if (!options.restitution && options.restitution !== 0)
  8050. options.restitution = 0.2;
  8051. }
  8052. this._physicImpostor = impostor;
  8053. this._physicsMass = options.mass;
  8054. this._physicsFriction = options.friction;
  8055. this._physicRestitution = options.restitution;
  8056. return physicsEngine._registerMesh(this, impostor, options);
  8057. };
  8058. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8059. if (!this._physicImpostor) {
  8060. return BABYLON.PhysicsEngine.NoImpostor;
  8061. }
  8062. return this._physicImpostor;
  8063. };
  8064. AbstractMesh.prototype.getPhysicsMass = function () {
  8065. if (!this._physicsMass) {
  8066. return 0;
  8067. }
  8068. return this._physicsMass;
  8069. };
  8070. AbstractMesh.prototype.getPhysicsFriction = function () {
  8071. if (!this._physicsFriction) {
  8072. return 0;
  8073. }
  8074. return this._physicsFriction;
  8075. };
  8076. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8077. if (!this._physicRestitution) {
  8078. return 0;
  8079. }
  8080. return this._physicRestitution;
  8081. };
  8082. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8083. if (!camera) {
  8084. camera = this.getScene().activeCamera;
  8085. }
  8086. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8087. };
  8088. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8089. if (!camera) {
  8090. camera = this.getScene().activeCamera;
  8091. }
  8092. return this.absolutePosition.subtract(camera.position).length();
  8093. };
  8094. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8095. if (!this._physicImpostor) {
  8096. return;
  8097. }
  8098. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8099. };
  8100. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8101. if (!this._physicImpostor) {
  8102. return;
  8103. }
  8104. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8105. };
  8106. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8107. if (!this._physicImpostor) {
  8108. return;
  8109. }
  8110. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8111. };
  8112. // Collisions
  8113. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8114. var globalPosition = this.getAbsolutePosition();
  8115. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8116. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8117. this._collider.radius = this.ellipsoid;
  8118. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8119. };
  8120. // Submeshes octree
  8121. /**
  8122. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8123. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8124. */
  8125. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8126. if (maxCapacity === void 0) { maxCapacity = 64; }
  8127. if (maxDepth === void 0) { maxDepth = 2; }
  8128. if (!this._submeshesOctree) {
  8129. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8130. }
  8131. this.computeWorldMatrix(true);
  8132. // Update octree
  8133. var bbox = this.getBoundingInfo().boundingBox;
  8134. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8135. return this._submeshesOctree;
  8136. };
  8137. // Collisions
  8138. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8139. this._generatePointsArray();
  8140. // Transformation
  8141. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8142. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8143. subMesh._lastColliderWorldVertices = [];
  8144. subMesh._trianglePlanes = [];
  8145. var start = subMesh.verticesStart;
  8146. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8147. for (var i = start; i < end; i++) {
  8148. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8149. }
  8150. }
  8151. // Collide
  8152. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8153. if (collider.collisionFound) {
  8154. collider.collidedMesh = this;
  8155. }
  8156. };
  8157. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8158. var subMeshes;
  8159. var len;
  8160. // Octrees
  8161. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8162. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8163. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8164. len = intersections.length;
  8165. subMeshes = intersections.data;
  8166. }
  8167. else {
  8168. subMeshes = this.subMeshes;
  8169. len = subMeshes.length;
  8170. }
  8171. for (var index = 0; index < len; index++) {
  8172. var subMesh = subMeshes[index];
  8173. // Bounding test
  8174. if (len > 1 && !subMesh._checkCollision(collider))
  8175. continue;
  8176. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8177. }
  8178. };
  8179. AbstractMesh.prototype._checkCollision = function (collider) {
  8180. // Bounding box test
  8181. if (!this._boundingInfo._checkCollision(collider))
  8182. return;
  8183. // Transformation matrix
  8184. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8185. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8186. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8187. };
  8188. // Picking
  8189. AbstractMesh.prototype._generatePointsArray = function () {
  8190. return false;
  8191. };
  8192. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8193. var pickingInfo = new BABYLON.PickingInfo();
  8194. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8195. return pickingInfo;
  8196. }
  8197. if (!this._generatePointsArray()) {
  8198. return pickingInfo;
  8199. }
  8200. var intersectInfo = null;
  8201. // Octrees
  8202. var subMeshes;
  8203. var len;
  8204. if (this._submeshesOctree && this.useOctreeForPicking) {
  8205. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8206. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8207. len = intersections.length;
  8208. subMeshes = intersections.data;
  8209. }
  8210. else {
  8211. subMeshes = this.subMeshes;
  8212. len = subMeshes.length;
  8213. }
  8214. for (var index = 0; index < len; index++) {
  8215. var subMesh = subMeshes[index];
  8216. // Bounding test
  8217. if (len > 1 && !subMesh.canIntersects(ray))
  8218. continue;
  8219. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8220. if (currentIntersectInfo) {
  8221. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8222. intersectInfo = currentIntersectInfo;
  8223. intersectInfo.subMeshId = index;
  8224. if (fastCheck) {
  8225. break;
  8226. }
  8227. }
  8228. }
  8229. }
  8230. if (intersectInfo) {
  8231. // Get picked point
  8232. var world = this.getWorldMatrix();
  8233. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8234. var direction = ray.direction.clone();
  8235. direction = direction.scale(intersectInfo.distance);
  8236. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8237. var pickedPoint = worldOrigin.add(worldDirection);
  8238. // Return result
  8239. pickingInfo.hit = true;
  8240. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8241. pickingInfo.pickedPoint = pickedPoint;
  8242. pickingInfo.pickedMesh = this;
  8243. pickingInfo.bu = intersectInfo.bu;
  8244. pickingInfo.bv = intersectInfo.bv;
  8245. pickingInfo.faceId = intersectInfo.faceId;
  8246. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8247. return pickingInfo;
  8248. }
  8249. return pickingInfo;
  8250. };
  8251. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8252. return null;
  8253. };
  8254. AbstractMesh.prototype.releaseSubMeshes = function () {
  8255. if (this.subMeshes) {
  8256. while (this.subMeshes.length) {
  8257. this.subMeshes[0].dispose();
  8258. }
  8259. }
  8260. else {
  8261. this.subMeshes = new Array();
  8262. }
  8263. };
  8264. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8265. var index;
  8266. // Physics
  8267. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8268. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8269. }
  8270. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8271. var other = this._intersectionsInProgress[index];
  8272. var pos = other._intersectionsInProgress.indexOf(this);
  8273. other._intersectionsInProgress.splice(pos, 1);
  8274. }
  8275. this._intersectionsInProgress = [];
  8276. // SubMeshes
  8277. this.releaseSubMeshes();
  8278. // Remove from scene
  8279. this.getScene().removeMesh(this);
  8280. if (!doNotRecurse) {
  8281. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8282. if (this.getScene().particleSystems[index].emitter === this) {
  8283. this.getScene().particleSystems[index].dispose();
  8284. index--;
  8285. }
  8286. }
  8287. // Children
  8288. var objects = this.getScene().meshes.slice(0);
  8289. for (index = 0; index < objects.length; index++) {
  8290. if (objects[index].parent === this) {
  8291. objects[index].dispose();
  8292. }
  8293. }
  8294. }
  8295. else {
  8296. for (index = 0; index < this.getScene().meshes.length; index++) {
  8297. var obj = this.getScene().meshes[index];
  8298. if (obj.parent === this) {
  8299. obj.parent = null;
  8300. obj.computeWorldMatrix(true);
  8301. }
  8302. }
  8303. }
  8304. this._onAfterWorldMatrixUpdate = [];
  8305. this._isDisposed = true;
  8306. // Callback
  8307. if (this.onDispose) {
  8308. this.onDispose();
  8309. }
  8310. };
  8311. // Statics
  8312. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8313. AbstractMesh._BILLBOARDMODE_X = 1;
  8314. AbstractMesh._BILLBOARDMODE_Y = 2;
  8315. AbstractMesh._BILLBOARDMODE_Z = 4;
  8316. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8317. return AbstractMesh;
  8318. })(BABYLON.Node);
  8319. BABYLON.AbstractMesh = AbstractMesh;
  8320. })(BABYLON || (BABYLON = {}));
  8321. //# sourceMappingURL=babylon.abstractMesh.js.map
  8322. var __extends = this.__extends || function (d, b) {
  8323. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8324. function __() { this.constructor = d; }
  8325. __.prototype = b.prototype;
  8326. d.prototype = new __();
  8327. };
  8328. var BABYLON;
  8329. (function (BABYLON) {
  8330. var Light = (function (_super) {
  8331. __extends(Light, _super);
  8332. function Light(name, scene) {
  8333. _super.call(this, name, scene);
  8334. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8335. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8336. this.intensity = 1.0;
  8337. this.range = Number.MAX_VALUE;
  8338. this.includeOnlyWithLayerMask = 0;
  8339. this.includedOnlyMeshes = new Array();
  8340. this.excludedMeshes = new Array();
  8341. this.excludeWithLayerMask = 0;
  8342. this._excludedMeshesIds = new Array();
  8343. this._includedOnlyMeshesIds = new Array();
  8344. scene.addLight(this);
  8345. }
  8346. Light.prototype.getShadowGenerator = function () {
  8347. return this._shadowGenerator;
  8348. };
  8349. Light.prototype.getAbsolutePosition = function () {
  8350. return BABYLON.Vector3.Zero();
  8351. };
  8352. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8353. };
  8354. Light.prototype._getWorldMatrix = function () {
  8355. return BABYLON.Matrix.Identity();
  8356. };
  8357. Light.prototype.canAffectMesh = function (mesh) {
  8358. if (!mesh) {
  8359. return true;
  8360. }
  8361. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8362. return false;
  8363. }
  8364. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8365. return false;
  8366. }
  8367. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8368. return false;
  8369. }
  8370. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8371. return false;
  8372. }
  8373. return true;
  8374. };
  8375. Light.prototype.getWorldMatrix = function () {
  8376. this._currentRenderId = this.getScene().getRenderId();
  8377. var worldMatrix = this._getWorldMatrix();
  8378. if (this.parent && this.parent.getWorldMatrix) {
  8379. if (!this._parentedWorldMatrix) {
  8380. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8381. }
  8382. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8383. this._markSyncedWithParent();
  8384. return this._parentedWorldMatrix;
  8385. }
  8386. return worldMatrix;
  8387. };
  8388. Light.prototype.dispose = function () {
  8389. if (this._shadowGenerator) {
  8390. this._shadowGenerator.dispose();
  8391. this._shadowGenerator = null;
  8392. }
  8393. // Remove from scene
  8394. this.getScene().removeLight(this);
  8395. };
  8396. return Light;
  8397. })(BABYLON.Node);
  8398. BABYLON.Light = Light;
  8399. })(BABYLON || (BABYLON = {}));
  8400. //# sourceMappingURL=babylon.light.js.map
  8401. var __extends = this.__extends || function (d, b) {
  8402. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8403. function __() { this.constructor = d; }
  8404. __.prototype = b.prototype;
  8405. d.prototype = new __();
  8406. };
  8407. var BABYLON;
  8408. (function (BABYLON) {
  8409. var PointLight = (function (_super) {
  8410. __extends(PointLight, _super);
  8411. function PointLight(name, position, scene) {
  8412. _super.call(this, name, scene);
  8413. this.position = position;
  8414. }
  8415. PointLight.prototype.getAbsolutePosition = function () {
  8416. return this._transformedPosition ? this._transformedPosition : this.position;
  8417. };
  8418. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8419. if (this.parent && this.parent.getWorldMatrix) {
  8420. if (!this._transformedPosition) {
  8421. this._transformedPosition = BABYLON.Vector3.Zero();
  8422. }
  8423. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8424. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8425. return;
  8426. }
  8427. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8428. };
  8429. PointLight.prototype.getShadowGenerator = function () {
  8430. return null;
  8431. };
  8432. PointLight.prototype._getWorldMatrix = function () {
  8433. if (!this._worldMatrix) {
  8434. this._worldMatrix = BABYLON.Matrix.Identity();
  8435. }
  8436. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8437. return this._worldMatrix;
  8438. };
  8439. return PointLight;
  8440. })(BABYLON.Light);
  8441. BABYLON.PointLight = PointLight;
  8442. })(BABYLON || (BABYLON = {}));
  8443. //# sourceMappingURL=babylon.pointLight.js.map
  8444. var __extends = this.__extends || function (d, b) {
  8445. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8446. function __() { this.constructor = d; }
  8447. __.prototype = b.prototype;
  8448. d.prototype = new __();
  8449. };
  8450. var BABYLON;
  8451. (function (BABYLON) {
  8452. var SpotLight = (function (_super) {
  8453. __extends(SpotLight, _super);
  8454. function SpotLight(name, position, direction, angle, exponent, scene) {
  8455. _super.call(this, name, scene);
  8456. this.position = position;
  8457. this.direction = direction;
  8458. this.angle = angle;
  8459. this.exponent = exponent;
  8460. }
  8461. SpotLight.prototype.getAbsolutePosition = function () {
  8462. return this.transformedPosition ? this.transformedPosition : this.position;
  8463. };
  8464. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8465. var activeCamera = this.getScene().activeCamera;
  8466. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8467. };
  8468. SpotLight.prototype.supportsVSM = function () {
  8469. return true;
  8470. };
  8471. SpotLight.prototype.needRefreshPerFrame = function () {
  8472. return false;
  8473. };
  8474. SpotLight.prototype.setDirectionToTarget = function (target) {
  8475. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8476. return this.direction;
  8477. };
  8478. SpotLight.prototype.computeTransformedPosition = function () {
  8479. if (this.parent && this.parent.getWorldMatrix) {
  8480. if (!this.transformedPosition) {
  8481. this.transformedPosition = BABYLON.Vector3.Zero();
  8482. }
  8483. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8484. return true;
  8485. }
  8486. return false;
  8487. };
  8488. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8489. var normalizeDirection;
  8490. if (this.parent && this.parent.getWorldMatrix) {
  8491. if (!this._transformedDirection) {
  8492. this._transformedDirection = BABYLON.Vector3.Zero();
  8493. }
  8494. this.computeTransformedPosition();
  8495. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8496. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8497. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8498. }
  8499. else {
  8500. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8501. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8502. }
  8503. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8504. };
  8505. SpotLight.prototype._getWorldMatrix = function () {
  8506. if (!this._worldMatrix) {
  8507. this._worldMatrix = BABYLON.Matrix.Identity();
  8508. }
  8509. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8510. return this._worldMatrix;
  8511. };
  8512. return SpotLight;
  8513. })(BABYLON.Light);
  8514. BABYLON.SpotLight = SpotLight;
  8515. })(BABYLON || (BABYLON = {}));
  8516. //# sourceMappingURL=babylon.spotLight.js.map
  8517. var __extends = this.__extends || function (d, b) {
  8518. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8519. function __() { this.constructor = d; }
  8520. __.prototype = b.prototype;
  8521. d.prototype = new __();
  8522. };
  8523. var BABYLON;
  8524. (function (BABYLON) {
  8525. var HemisphericLight = (function (_super) {
  8526. __extends(HemisphericLight, _super);
  8527. function HemisphericLight(name, direction, scene) {
  8528. _super.call(this, name, scene);
  8529. this.direction = direction;
  8530. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8531. }
  8532. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8533. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8534. return this.direction;
  8535. };
  8536. HemisphericLight.prototype.getShadowGenerator = function () {
  8537. return null;
  8538. };
  8539. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8540. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8541. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8542. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8543. };
  8544. HemisphericLight.prototype._getWorldMatrix = function () {
  8545. if (!this._worldMatrix) {
  8546. this._worldMatrix = BABYLON.Matrix.Identity();
  8547. }
  8548. return this._worldMatrix;
  8549. };
  8550. return HemisphericLight;
  8551. })(BABYLON.Light);
  8552. BABYLON.HemisphericLight = HemisphericLight;
  8553. })(BABYLON || (BABYLON = {}));
  8554. //# sourceMappingURL=babylon.hemisphericLight.js.map
  8555. var __extends = this.__extends || function (d, b) {
  8556. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8557. function __() { this.constructor = d; }
  8558. __.prototype = b.prototype;
  8559. d.prototype = new __();
  8560. };
  8561. var BABYLON;
  8562. (function (BABYLON) {
  8563. var DirectionalLight = (function (_super) {
  8564. __extends(DirectionalLight, _super);
  8565. function DirectionalLight(name, direction, scene) {
  8566. _super.call(this, name, scene);
  8567. this.direction = direction;
  8568. this.shadowOrthoScale = 0.5;
  8569. this.position = direction.scale(-1);
  8570. }
  8571. DirectionalLight.prototype.getAbsolutePosition = function () {
  8572. return this.transformedPosition ? this.transformedPosition : this.position;
  8573. };
  8574. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8575. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8576. return this.direction;
  8577. };
  8578. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8579. var orthoLeft = Number.MAX_VALUE;
  8580. var orthoRight = Number.MIN_VALUE;
  8581. var orthoTop = Number.MIN_VALUE;
  8582. var orthoBottom = Number.MAX_VALUE;
  8583. var tempVector3 = BABYLON.Vector3.Zero();
  8584. var activeCamera = this.getScene().activeCamera;
  8585. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8586. var mesh = renderList[meshIndex];
  8587. if (!mesh) {
  8588. continue;
  8589. }
  8590. var boundingInfo = mesh.getBoundingInfo();
  8591. if (!boundingInfo) {
  8592. continue;
  8593. }
  8594. var boundingBox = boundingInfo.boundingBox;
  8595. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8596. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8597. if (tempVector3.x < orthoLeft)
  8598. orthoLeft = tempVector3.x;
  8599. if (tempVector3.y < orthoBottom)
  8600. orthoBottom = tempVector3.y;
  8601. if (tempVector3.x > orthoRight)
  8602. orthoRight = tempVector3.x;
  8603. if (tempVector3.y > orthoTop)
  8604. orthoTop = tempVector3.y;
  8605. }
  8606. }
  8607. var xOffset = orthoRight - orthoLeft;
  8608. var yOffset = orthoTop - orthoBottom;
  8609. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8610. };
  8611. DirectionalLight.prototype.supportsVSM = function () {
  8612. return true;
  8613. };
  8614. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8615. return true;
  8616. };
  8617. DirectionalLight.prototype.computeTransformedPosition = function () {
  8618. if (this.parent && this.parent.getWorldMatrix) {
  8619. if (!this.transformedPosition) {
  8620. this.transformedPosition = BABYLON.Vector3.Zero();
  8621. }
  8622. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8623. return true;
  8624. }
  8625. return false;
  8626. };
  8627. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8628. if (this.parent && this.parent.getWorldMatrix) {
  8629. if (!this._transformedDirection) {
  8630. this._transformedDirection = BABYLON.Vector3.Zero();
  8631. }
  8632. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8633. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8634. return;
  8635. }
  8636. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8637. };
  8638. DirectionalLight.prototype._getWorldMatrix = function () {
  8639. if (!this._worldMatrix) {
  8640. this._worldMatrix = BABYLON.Matrix.Identity();
  8641. }
  8642. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8643. return this._worldMatrix;
  8644. };
  8645. return DirectionalLight;
  8646. })(BABYLON.Light);
  8647. BABYLON.DirectionalLight = DirectionalLight;
  8648. })(BABYLON || (BABYLON = {}));
  8649. //# sourceMappingURL=babylon.directionalLight.js.map
  8650. var BABYLON;
  8651. (function (BABYLON) {
  8652. var ShadowGenerator = (function () {
  8653. function ShadowGenerator(mapSize, light) {
  8654. var _this = this;
  8655. // Members
  8656. this._filter = ShadowGenerator.FILTER_NONE;
  8657. this.blurScale = 2;
  8658. this._blurBoxOffset = 0;
  8659. this._bias = 0.00005;
  8660. this._darkness = 0;
  8661. this._transparencyShadow = false;
  8662. this._viewMatrix = BABYLON.Matrix.Zero();
  8663. this._projectionMatrix = BABYLON.Matrix.Zero();
  8664. this._transformMatrix = BABYLON.Matrix.Zero();
  8665. this._worldViewProjection = BABYLON.Matrix.Zero();
  8666. this._light = light;
  8667. this._scene = light.getScene();
  8668. this._mapSize = mapSize;
  8669. light._shadowGenerator = this;
  8670. // Render target
  8671. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8672. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8673. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8674. this._shadowMap.anisotropicFilteringLevel = 1;
  8675. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8676. this._shadowMap.renderParticles = false;
  8677. this._shadowMap.onAfterUnbind = function () {
  8678. if (!_this.useBlurVarianceShadowMap) {
  8679. return;
  8680. }
  8681. if (!_this._shadowMap2) {
  8682. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8683. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8684. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8685. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8686. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8687. _this._downSamplePostprocess.onApply = function (effect) {
  8688. effect.setTexture("textureSampler", _this._shadowMap);
  8689. };
  8690. _this.blurBoxOffset = 1;
  8691. }
  8692. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8693. };
  8694. // Custom render function
  8695. var renderSubMesh = function (subMesh) {
  8696. var mesh = subMesh.getRenderingMesh();
  8697. var scene = _this._scene;
  8698. var engine = scene.getEngine();
  8699. // Culling
  8700. engine.setState(subMesh.getMaterial().backFaceCulling);
  8701. // Managing instances
  8702. var batch = mesh._getInstancesRenderList(subMesh._id);
  8703. if (batch.mustReturn) {
  8704. return;
  8705. }
  8706. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8707. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8708. engine.enableEffect(_this._effect);
  8709. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8710. var material = subMesh.getMaterial();
  8711. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8712. // Alpha test
  8713. if (material && material.needAlphaTesting()) {
  8714. var alphaTexture = material.getAlphaTestTexture();
  8715. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8716. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8717. }
  8718. // Bones
  8719. if (mesh.useBones) {
  8720. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8721. }
  8722. // Draw
  8723. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8724. }
  8725. else {
  8726. // Need to reset refresh rate of the shadowMap
  8727. _this._shadowMap.resetRefreshCounter();
  8728. }
  8729. };
  8730. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8731. var index;
  8732. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8733. renderSubMesh(opaqueSubMeshes.data[index]);
  8734. }
  8735. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8736. renderSubMesh(alphaTestSubMeshes.data[index]);
  8737. }
  8738. if (_this._transparencyShadow) {
  8739. for (index = 0; index < transparentSubMeshes.length; index++) {
  8740. renderSubMesh(transparentSubMeshes.data[index]);
  8741. }
  8742. }
  8743. };
  8744. this._shadowMap.onClear = function (engine) {
  8745. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8746. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8747. }
  8748. else {
  8749. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8750. }
  8751. };
  8752. }
  8753. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8754. // Static
  8755. get: function () {
  8756. return ShadowGenerator._FILTER_NONE;
  8757. },
  8758. enumerable: true,
  8759. configurable: true
  8760. });
  8761. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8762. get: function () {
  8763. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8764. },
  8765. enumerable: true,
  8766. configurable: true
  8767. });
  8768. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8769. get: function () {
  8770. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8771. },
  8772. enumerable: true,
  8773. configurable: true
  8774. });
  8775. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8776. get: function () {
  8777. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8778. },
  8779. enumerable: true,
  8780. configurable: true
  8781. });
  8782. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8783. get: function () {
  8784. return this._bias;
  8785. },
  8786. set: function (bias) {
  8787. this._bias = bias;
  8788. },
  8789. enumerable: true,
  8790. configurable: true
  8791. });
  8792. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8793. get: function () {
  8794. return this._blurBoxOffset;
  8795. },
  8796. set: function (value) {
  8797. var _this = this;
  8798. if (this._blurBoxOffset === value) {
  8799. return;
  8800. }
  8801. this._blurBoxOffset = value;
  8802. if (this._boxBlurPostprocess) {
  8803. this._boxBlurPostprocess.dispose();
  8804. }
  8805. 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);
  8806. this._boxBlurPostprocess.onApply = function (effect) {
  8807. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8808. };
  8809. },
  8810. enumerable: true,
  8811. configurable: true
  8812. });
  8813. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8814. get: function () {
  8815. return this._filter;
  8816. },
  8817. set: function (value) {
  8818. if (this._filter === value) {
  8819. return;
  8820. }
  8821. this._filter = value;
  8822. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8823. this._shadowMap.anisotropicFilteringLevel = 16;
  8824. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8825. }
  8826. else {
  8827. this._shadowMap.anisotropicFilteringLevel = 1;
  8828. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8829. }
  8830. },
  8831. enumerable: true,
  8832. configurable: true
  8833. });
  8834. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8835. get: function () {
  8836. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8837. },
  8838. set: function (value) {
  8839. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8840. },
  8841. enumerable: true,
  8842. configurable: true
  8843. });
  8844. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8845. get: function () {
  8846. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8847. },
  8848. set: function (value) {
  8849. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8850. },
  8851. enumerable: true,
  8852. configurable: true
  8853. });
  8854. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8855. get: function () {
  8856. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8857. },
  8858. set: function (value) {
  8859. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8860. },
  8861. enumerable: true,
  8862. configurable: true
  8863. });
  8864. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8865. var defines = [];
  8866. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8867. defines.push("#define VSM");
  8868. }
  8869. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8870. var mesh = subMesh.getMesh();
  8871. var material = subMesh.getMaterial();
  8872. // Alpha test
  8873. if (material && material.needAlphaTesting()) {
  8874. defines.push("#define ALPHATEST");
  8875. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8876. attribs.push(BABYLON.VertexBuffer.UVKind);
  8877. defines.push("#define UV1");
  8878. }
  8879. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8880. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8881. defines.push("#define UV2");
  8882. }
  8883. }
  8884. // Bones
  8885. if (mesh.useBones) {
  8886. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8887. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8888. defines.push("#define BONES");
  8889. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8890. }
  8891. // Instances
  8892. if (useInstances) {
  8893. defines.push("#define INSTANCES");
  8894. attribs.push("world0");
  8895. attribs.push("world1");
  8896. attribs.push("world2");
  8897. attribs.push("world3");
  8898. }
  8899. // Get correct effect
  8900. var join = defines.join("\n");
  8901. if (this._cachedDefines !== join) {
  8902. this._cachedDefines = join;
  8903. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8904. }
  8905. return this._effect.isReady();
  8906. };
  8907. ShadowGenerator.prototype.getShadowMap = function () {
  8908. return this._shadowMap;
  8909. };
  8910. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8911. if (this._shadowMap2) {
  8912. return this._shadowMap2;
  8913. }
  8914. return this._shadowMap;
  8915. };
  8916. ShadowGenerator.prototype.getLight = function () {
  8917. return this._light;
  8918. };
  8919. // Methods
  8920. ShadowGenerator.prototype.getTransformMatrix = function () {
  8921. var scene = this._scene;
  8922. if (this._currentRenderID === scene.getRenderId()) {
  8923. return this._transformMatrix;
  8924. }
  8925. this._currentRenderID = scene.getRenderId();
  8926. var lightPosition = this._light.position;
  8927. var lightDirection = this._light.direction;
  8928. if (this._light.computeTransformedPosition()) {
  8929. lightPosition = this._light.transformedPosition;
  8930. }
  8931. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  8932. this._cachedPosition = lightPosition.clone();
  8933. this._cachedDirection = lightDirection.clone();
  8934. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8935. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8936. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8937. }
  8938. return this._transformMatrix;
  8939. };
  8940. ShadowGenerator.prototype.getDarkness = function () {
  8941. return this._darkness;
  8942. };
  8943. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8944. if (darkness >= 1.0)
  8945. this._darkness = 1.0;
  8946. else if (darkness <= 0.0)
  8947. this._darkness = 0.0;
  8948. else
  8949. this._darkness = darkness;
  8950. };
  8951. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8952. this._transparencyShadow = hasShadow;
  8953. };
  8954. ShadowGenerator.prototype._packHalf = function (depth) {
  8955. var scale = depth * 255.0;
  8956. var fract = scale - Math.floor(scale);
  8957. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8958. };
  8959. ShadowGenerator.prototype.dispose = function () {
  8960. this._shadowMap.dispose();
  8961. if (this._shadowMap2) {
  8962. this._shadowMap2.dispose();
  8963. }
  8964. if (this._downSamplePostprocess) {
  8965. this._downSamplePostprocess.dispose();
  8966. }
  8967. if (this._boxBlurPostprocess) {
  8968. this._boxBlurPostprocess.dispose();
  8969. }
  8970. };
  8971. ShadowGenerator._FILTER_NONE = 0;
  8972. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  8973. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  8974. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  8975. return ShadowGenerator;
  8976. })();
  8977. BABYLON.ShadowGenerator = ShadowGenerator;
  8978. })(BABYLON || (BABYLON = {}));
  8979. //# sourceMappingURL=babylon.shadowGenerator.js.map
  8980. var BABYLON;
  8981. (function (BABYLON) {
  8982. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  8983. if (boxMin.x > sphereCenter.x + sphereRadius)
  8984. return false;
  8985. if (sphereCenter.x - sphereRadius > boxMax.x)
  8986. return false;
  8987. if (boxMin.y > sphereCenter.y + sphereRadius)
  8988. return false;
  8989. if (sphereCenter.y - sphereRadius > boxMax.y)
  8990. return false;
  8991. if (boxMin.z > sphereCenter.z + sphereRadius)
  8992. return false;
  8993. if (sphereCenter.z - sphereRadius > boxMax.z)
  8994. return false;
  8995. return true;
  8996. };
  8997. var getLowestRoot = function (a, b, c, maxR) {
  8998. var determinant = b * b - 4.0 * a * c;
  8999. var result = { root: 0, found: false };
  9000. if (determinant < 0)
  9001. return result;
  9002. var sqrtD = Math.sqrt(determinant);
  9003. var r1 = (-b - sqrtD) / (2.0 * a);
  9004. var r2 = (-b + sqrtD) / (2.0 * a);
  9005. if (r1 > r2) {
  9006. var temp = r2;
  9007. r2 = r1;
  9008. r1 = temp;
  9009. }
  9010. if (r1 > 0 && r1 < maxR) {
  9011. result.root = r1;
  9012. result.found = true;
  9013. return result;
  9014. }
  9015. if (r2 > 0 && r2 < maxR) {
  9016. result.root = r2;
  9017. result.found = true;
  9018. return result;
  9019. }
  9020. return result;
  9021. };
  9022. var Collider = (function () {
  9023. function Collider() {
  9024. this.radius = new BABYLON.Vector3(1, 1, 1);
  9025. this.retry = 0;
  9026. this.basePointWorld = BABYLON.Vector3.Zero();
  9027. this.velocityWorld = BABYLON.Vector3.Zero();
  9028. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9029. this._collisionPoint = BABYLON.Vector3.Zero();
  9030. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9031. this._tempVector = BABYLON.Vector3.Zero();
  9032. this._tempVector2 = BABYLON.Vector3.Zero();
  9033. this._tempVector3 = BABYLON.Vector3.Zero();
  9034. this._tempVector4 = BABYLON.Vector3.Zero();
  9035. this._edge = BABYLON.Vector3.Zero();
  9036. this._baseToVertex = BABYLON.Vector3.Zero();
  9037. this._destinationPoint = BABYLON.Vector3.Zero();
  9038. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9039. this._displacementVector = BABYLON.Vector3.Zero();
  9040. }
  9041. // Methods
  9042. Collider.prototype._initialize = function (source, dir, e) {
  9043. this.velocity = dir;
  9044. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9045. this.basePoint = source;
  9046. source.multiplyToRef(this.radius, this.basePointWorld);
  9047. dir.multiplyToRef(this.radius, this.velocityWorld);
  9048. this.velocityWorldLength = this.velocityWorld.length();
  9049. this.epsilon = e;
  9050. this.collisionFound = false;
  9051. };
  9052. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9053. pa.subtractToRef(point, this._tempVector);
  9054. pb.subtractToRef(point, this._tempVector2);
  9055. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9056. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9057. if (d < 0)
  9058. return false;
  9059. pc.subtractToRef(point, this._tempVector3);
  9060. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9061. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9062. if (d < 0)
  9063. return false;
  9064. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9065. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9066. return d >= 0;
  9067. };
  9068. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9069. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9070. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9071. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9072. return false;
  9073. }
  9074. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9075. return false;
  9076. return true;
  9077. };
  9078. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9079. var t0;
  9080. var embeddedInPlane = false;
  9081. //defensive programming, actually not needed.
  9082. if (!trianglePlaneArray) {
  9083. trianglePlaneArray = [];
  9084. }
  9085. if (!trianglePlaneArray[faceIndex]) {
  9086. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9087. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9088. }
  9089. var trianglePlane = trianglePlaneArray[faceIndex];
  9090. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9091. return;
  9092. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9093. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9094. if (normalDotVelocity == 0) {
  9095. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9096. return;
  9097. embeddedInPlane = true;
  9098. t0 = 0;
  9099. }
  9100. else {
  9101. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9102. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9103. if (t0 > t1) {
  9104. var temp = t1;
  9105. t1 = t0;
  9106. t0 = temp;
  9107. }
  9108. if (t0 > 1.0 || t1 < 0.0)
  9109. return;
  9110. if (t0 < 0)
  9111. t0 = 0;
  9112. if (t0 > 1.0)
  9113. t0 = 1.0;
  9114. }
  9115. this._collisionPoint.copyFromFloats(0, 0, 0);
  9116. var found = false;
  9117. var t = 1.0;
  9118. if (!embeddedInPlane) {
  9119. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9120. this.velocity.scaleToRef(t0, this._tempVector);
  9121. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9122. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9123. found = true;
  9124. t = t0;
  9125. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9126. }
  9127. }
  9128. if (!found) {
  9129. var velocitySquaredLength = this.velocity.lengthSquared();
  9130. var a = velocitySquaredLength;
  9131. this.basePoint.subtractToRef(p1, this._tempVector);
  9132. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9133. var c = this._tempVector.lengthSquared() - 1.0;
  9134. var lowestRoot = getLowestRoot(a, b, c, t);
  9135. if (lowestRoot.found) {
  9136. t = lowestRoot.root;
  9137. found = true;
  9138. this._collisionPoint.copyFrom(p1);
  9139. }
  9140. this.basePoint.subtractToRef(p2, this._tempVector);
  9141. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9142. c = this._tempVector.lengthSquared() - 1.0;
  9143. lowestRoot = getLowestRoot(a, b, c, t);
  9144. if (lowestRoot.found) {
  9145. t = lowestRoot.root;
  9146. found = true;
  9147. this._collisionPoint.copyFrom(p2);
  9148. }
  9149. this.basePoint.subtractToRef(p3, this._tempVector);
  9150. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9151. c = this._tempVector.lengthSquared() - 1.0;
  9152. lowestRoot = getLowestRoot(a, b, c, t);
  9153. if (lowestRoot.found) {
  9154. t = lowestRoot.root;
  9155. found = true;
  9156. this._collisionPoint.copyFrom(p3);
  9157. }
  9158. p2.subtractToRef(p1, this._edge);
  9159. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9160. var edgeSquaredLength = this._edge.lengthSquared();
  9161. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9162. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9163. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9164. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9165. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9166. lowestRoot = getLowestRoot(a, b, c, t);
  9167. if (lowestRoot.found) {
  9168. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9169. if (f >= 0.0 && f <= 1.0) {
  9170. t = lowestRoot.root;
  9171. found = true;
  9172. this._edge.scaleInPlace(f);
  9173. p1.addToRef(this._edge, this._collisionPoint);
  9174. }
  9175. }
  9176. p3.subtractToRef(p2, this._edge);
  9177. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9178. edgeSquaredLength = this._edge.lengthSquared();
  9179. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9180. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9181. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9182. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9183. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9184. lowestRoot = getLowestRoot(a, b, c, t);
  9185. if (lowestRoot.found) {
  9186. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9187. if (f >= 0.0 && f <= 1.0) {
  9188. t = lowestRoot.root;
  9189. found = true;
  9190. this._edge.scaleInPlace(f);
  9191. p2.addToRef(this._edge, this._collisionPoint);
  9192. }
  9193. }
  9194. p1.subtractToRef(p3, this._edge);
  9195. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9196. edgeSquaredLength = this._edge.lengthSquared();
  9197. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9198. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9199. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9200. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9201. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9202. lowestRoot = getLowestRoot(a, b, c, t);
  9203. if (lowestRoot.found) {
  9204. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9205. if (f >= 0.0 && f <= 1.0) {
  9206. t = lowestRoot.root;
  9207. found = true;
  9208. this._edge.scaleInPlace(f);
  9209. p3.addToRef(this._edge, this._collisionPoint);
  9210. }
  9211. }
  9212. }
  9213. if (found) {
  9214. var distToCollision = t * this.velocity.length();
  9215. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9216. if (!this.intersectionPoint) {
  9217. this.intersectionPoint = this._collisionPoint.clone();
  9218. }
  9219. else {
  9220. this.intersectionPoint.copyFrom(this._collisionPoint);
  9221. }
  9222. this.nearestDistance = distToCollision;
  9223. this.collisionFound = true;
  9224. }
  9225. }
  9226. };
  9227. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9228. for (var i = indexStart; i < indexEnd; i += 3) {
  9229. var p1 = pts[indices[i] - decal];
  9230. var p2 = pts[indices[i + 1] - decal];
  9231. var p3 = pts[indices[i + 2] - decal];
  9232. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9233. }
  9234. };
  9235. Collider.prototype._getResponse = function (pos, vel) {
  9236. pos.addToRef(vel, this._destinationPoint);
  9237. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9238. this.basePoint.addToRef(vel, pos);
  9239. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9240. this._slidePlaneNormal.normalize();
  9241. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9242. pos.addInPlace(this._displacementVector);
  9243. this.intersectionPoint.addInPlace(this._displacementVector);
  9244. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9245. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9246. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9247. };
  9248. return Collider;
  9249. })();
  9250. BABYLON.Collider = Collider;
  9251. })(BABYLON || (BABYLON = {}));
  9252. //# sourceMappingURL=babylon.collider.js.map
  9253. var BABYLON;
  9254. (function (BABYLON) {
  9255. //WebWorker code will be inserted to this variable.
  9256. BABYLON.CollisionWorker = "";
  9257. (function (WorkerTaskType) {
  9258. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9259. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9260. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9261. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9262. var WorkerTaskType = BABYLON.WorkerTaskType;
  9263. (function (WorkerReplyType) {
  9264. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9265. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9266. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9267. var WorkerReplyType = BABYLON.WorkerReplyType;
  9268. var CollisionCoordinatorWorker = (function () {
  9269. function CollisionCoordinatorWorker() {
  9270. var _this = this;
  9271. this._scaledPosition = BABYLON.Vector3.Zero();
  9272. this._scaledVelocity = BABYLON.Vector3.Zero();
  9273. this.onMeshUpdated = function (mesh) {
  9274. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9275. };
  9276. this.onGeometryUpdated = function (geometry) {
  9277. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9278. };
  9279. this._afterRender = function () {
  9280. if (!_this._init)
  9281. return;
  9282. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9283. return;
  9284. }
  9285. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9286. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9287. if (_this._runningUpdated > 4) {
  9288. return;
  9289. }
  9290. ++_this._runningUpdated;
  9291. var payload = {
  9292. updatedMeshes: _this._addUpdateMeshesList,
  9293. updatedGeometries: _this._addUpdateGeometriesList,
  9294. removedGeometries: _this._toRemoveGeometryArray,
  9295. removedMeshes: _this._toRemoveMeshesArray
  9296. };
  9297. var message = {
  9298. payload: payload,
  9299. taskType: 1 /* UPDATE */
  9300. };
  9301. var serializable = [];
  9302. for (var id in payload.updatedGeometries) {
  9303. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9304. //prepare transferables
  9305. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9306. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9307. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9308. }
  9309. }
  9310. _this._worker.postMessage(message, serializable);
  9311. _this._addUpdateMeshesList = {};
  9312. _this._addUpdateGeometriesList = {};
  9313. _this._toRemoveGeometryArray = [];
  9314. _this._toRemoveMeshesArray = [];
  9315. };
  9316. this._onMessageFromWorker = function (e) {
  9317. var returnData = e.data;
  9318. if (returnData.error != 0 /* SUCCESS */) {
  9319. //TODO what errors can be returned from the worker?
  9320. BABYLON.Tools.Warn("error returned from worker!");
  9321. return;
  9322. }
  9323. switch (returnData.taskType) {
  9324. case 0 /* INIT */:
  9325. _this._init = true;
  9326. //Update the worked with ALL of the scene's current state
  9327. _this._scene.meshes.forEach(function (mesh) {
  9328. _this.onMeshAdded(mesh);
  9329. });
  9330. _this._scene.getGeometries().forEach(function (geometry) {
  9331. _this.onGeometryAdded(geometry);
  9332. });
  9333. break;
  9334. case 1 /* UPDATE */:
  9335. _this._runningUpdated--;
  9336. break;
  9337. case 2 /* COLLIDE */:
  9338. _this._runningCollisionTask = false;
  9339. var returnPayload = returnData.payload;
  9340. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9341. return;
  9342. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9343. //cleanup
  9344. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9345. break;
  9346. }
  9347. };
  9348. this._collisionsCallbackArray = [];
  9349. this._init = false;
  9350. this._runningUpdated = 0;
  9351. this._runningCollisionTask = false;
  9352. this._addUpdateMeshesList = {};
  9353. this._addUpdateGeometriesList = {};
  9354. this._toRemoveGeometryArray = [];
  9355. this._toRemoveMeshesArray = [];
  9356. }
  9357. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9358. if (!this._init)
  9359. return;
  9360. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9361. return;
  9362. position.divideToRef(collider.radius, this._scaledPosition);
  9363. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9364. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9365. var payload = {
  9366. collider: {
  9367. position: this._scaledPosition.asArray(),
  9368. velocity: this._scaledVelocity.asArray(),
  9369. radius: collider.radius.asArray()
  9370. },
  9371. collisionId: collisionIndex,
  9372. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9373. maximumRetry: maximumRetry
  9374. };
  9375. var message = {
  9376. payload: payload,
  9377. taskType: 2 /* COLLIDE */
  9378. };
  9379. this._worker.postMessage(message);
  9380. };
  9381. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9382. this._scene = scene;
  9383. this._scene.registerAfterRender(this._afterRender);
  9384. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9385. this._worker = new Worker(workerUrl);
  9386. this._worker.onmessage = this._onMessageFromWorker;
  9387. var message = {
  9388. payload: {},
  9389. taskType: 0 /* INIT */
  9390. };
  9391. this._worker.postMessage(message);
  9392. };
  9393. CollisionCoordinatorWorker.prototype.destroy = function () {
  9394. this._scene.unregisterAfterRender(this._afterRender);
  9395. this._worker.terminate();
  9396. };
  9397. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9398. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9399. this.onMeshUpdated(mesh);
  9400. };
  9401. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9402. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9403. };
  9404. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9405. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9406. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9407. this.onGeometryUpdated(geometry);
  9408. };
  9409. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9410. this._toRemoveGeometryArray.push(geometry.id);
  9411. };
  9412. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9413. var submeshes = [];
  9414. if (mesh.subMeshes) {
  9415. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9416. return {
  9417. position: idx,
  9418. verticesStart: sm.verticesStart,
  9419. verticesCount: sm.verticesCount,
  9420. indexStart: sm.indexStart,
  9421. indexCount: sm.indexCount,
  9422. hasMaterial: !!sm.getMaterial(),
  9423. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9424. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9425. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9426. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9427. };
  9428. });
  9429. }
  9430. var geometryId = mesh.geometry ? mesh.geometry.id : null;
  9431. return {
  9432. uniqueId: mesh.uniqueId,
  9433. id: mesh.id,
  9434. name: mesh.name,
  9435. geometryId: geometryId,
  9436. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9437. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9438. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9439. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9440. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9441. subMeshes: submeshes,
  9442. checkCollisions: mesh.checkCollisions
  9443. };
  9444. };
  9445. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9446. return {
  9447. id: geometry.id,
  9448. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9449. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9450. indices: new Int32Array(geometry.getIndices() || []),
  9451. };
  9452. };
  9453. return CollisionCoordinatorWorker;
  9454. })();
  9455. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9456. var CollisionCoordinatorLegacy = (function () {
  9457. function CollisionCoordinatorLegacy() {
  9458. this._scaledPosition = BABYLON.Vector3.Zero();
  9459. this._scaledVelocity = BABYLON.Vector3.Zero();
  9460. this._finalPosition = BABYLON.Vector3.Zero();
  9461. }
  9462. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9463. position.divideToRef(collider.radius, this._scaledPosition);
  9464. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9465. collider.retry = 0;
  9466. collider.initialVelocity = this._scaledVelocity;
  9467. collider.initialPosition = this._scaledPosition;
  9468. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9469. this._finalPosition.multiplyInPlace(collider.radius);
  9470. //run the callback
  9471. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9472. };
  9473. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9474. this._scene = scene;
  9475. };
  9476. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9477. //Legacy need no destruction method.
  9478. };
  9479. //No update in legacy mode
  9480. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) {
  9481. };
  9482. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) {
  9483. };
  9484. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) {
  9485. };
  9486. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) {
  9487. };
  9488. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) {
  9489. };
  9490. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) {
  9491. };
  9492. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9493. if (excludedMesh === void 0) { excludedMesh = null; }
  9494. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9495. if (collider.retry >= maximumRetry) {
  9496. finalPosition.copyFrom(position);
  9497. return;
  9498. }
  9499. collider._initialize(position, velocity, closeDistance);
  9500. for (var index = 0; index < this._scene.meshes.length; index++) {
  9501. var mesh = this._scene.meshes[index];
  9502. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9503. mesh._checkCollision(collider);
  9504. }
  9505. }
  9506. if (!collider.collisionFound) {
  9507. position.addToRef(velocity, finalPosition);
  9508. return;
  9509. }
  9510. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9511. collider._getResponse(position, velocity);
  9512. }
  9513. if (velocity.length() <= closeDistance) {
  9514. finalPosition.copyFrom(position);
  9515. return;
  9516. }
  9517. collider.retry++;
  9518. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9519. };
  9520. return CollisionCoordinatorLegacy;
  9521. })();
  9522. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9523. })(BABYLON || (BABYLON = {}));
  9524. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  9525. var __extends = this.__extends || function (d, b) {
  9526. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9527. function __() { this.constructor = d; }
  9528. __.prototype = b.prototype;
  9529. d.prototype = new __();
  9530. };
  9531. var BABYLON;
  9532. (function (BABYLON) {
  9533. var VRCameraMetrics = (function () {
  9534. function VRCameraMetrics() {
  9535. this.compensateDistorsion = true;
  9536. }
  9537. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9538. get: function () {
  9539. return this.hResolution / (2 * this.vResolution);
  9540. },
  9541. enumerable: true,
  9542. configurable: true
  9543. });
  9544. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9545. get: function () {
  9546. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9547. },
  9548. enumerable: true,
  9549. configurable: true
  9550. });
  9551. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9552. get: function () {
  9553. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9554. var h = (4 * meters) / this.hScreenSize;
  9555. return BABYLON.Matrix.Translation(h, 0, 0);
  9556. },
  9557. enumerable: true,
  9558. configurable: true
  9559. });
  9560. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9561. get: function () {
  9562. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9563. var h = (4 * meters) / this.hScreenSize;
  9564. return BABYLON.Matrix.Translation(-h, 0, 0);
  9565. },
  9566. enumerable: true,
  9567. configurable: true
  9568. });
  9569. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9570. get: function () {
  9571. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9572. },
  9573. enumerable: true,
  9574. configurable: true
  9575. });
  9576. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9577. get: function () {
  9578. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9579. },
  9580. enumerable: true,
  9581. configurable: true
  9582. });
  9583. VRCameraMetrics.GetDefault = function () {
  9584. var result = new VRCameraMetrics();
  9585. result.hResolution = 1280;
  9586. result.vResolution = 800;
  9587. result.hScreenSize = 0.149759993;
  9588. result.vScreenSize = 0.0935999975;
  9589. result.vScreenCenter = 0.0467999987, result.eyeToScreenDistance = 0.0410000011;
  9590. result.lensSeparationDistance = 0.0635000020;
  9591. result.interpupillaryDistance = 0.0640000030;
  9592. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9593. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9594. result.postProcessScaleFactor = 1.714605507808412;
  9595. result.lensCenterOffset = 0.151976421;
  9596. return result;
  9597. };
  9598. return VRCameraMetrics;
  9599. })();
  9600. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9601. var Camera = (function (_super) {
  9602. __extends(Camera, _super);
  9603. function Camera(name, position, scene) {
  9604. _super.call(this, name, scene);
  9605. this.position = position;
  9606. // Members
  9607. this.upVector = BABYLON.Vector3.Up();
  9608. this.orthoLeft = null;
  9609. this.orthoRight = null;
  9610. this.orthoBottom = null;
  9611. this.orthoTop = null;
  9612. this.fov = 0.8;
  9613. this.minZ = 1.0;
  9614. this.maxZ = 10000.0;
  9615. this.inertia = 0.9;
  9616. this.mode = Camera.PERSPECTIVE_CAMERA;
  9617. this.isIntermediate = false;
  9618. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9619. this.layerMask = 0x0FFFFFFF;
  9620. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9621. // Subcamera members
  9622. this.subCameras = new Array();
  9623. this._subCameraMode = Camera.SUB_CAMERA_MODE_NONE;
  9624. // Cache
  9625. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9626. this._projectionMatrix = new BABYLON.Matrix();
  9627. this._postProcesses = new Array();
  9628. this._postProcessesTakenIndices = [];
  9629. this._activeMeshes = new BABYLON.SmartArray(256);
  9630. this._globalPosition = BABYLON.Vector3.Zero();
  9631. scene.addCamera(this);
  9632. if (!scene.activeCamera) {
  9633. scene.activeCamera = this;
  9634. }
  9635. }
  9636. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9637. get: function () {
  9638. return Camera._PERSPECTIVE_CAMERA;
  9639. },
  9640. enumerable: true,
  9641. configurable: true
  9642. });
  9643. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9644. get: function () {
  9645. return Camera._ORTHOGRAPHIC_CAMERA;
  9646. },
  9647. enumerable: true,
  9648. configurable: true
  9649. });
  9650. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9651. get: function () {
  9652. return Camera._FOVMODE_VERTICAL_FIXED;
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9658. get: function () {
  9659. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9660. },
  9661. enumerable: true,
  9662. configurable: true
  9663. });
  9664. Object.defineProperty(Camera, "SUB_CAMERA_MODE_NONE", {
  9665. get: function () {
  9666. return Camera._SUB_CAMERA_MODE_NONE;
  9667. },
  9668. enumerable: true,
  9669. configurable: true
  9670. });
  9671. Object.defineProperty(Camera, "SUB_CAMERA_MODE_ANAGLYPH", {
  9672. get: function () {
  9673. return Camera._SUB_CAMERA_MODE_ANAGLYPH;
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. Object.defineProperty(Camera, "SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM", {
  9679. get: function () {
  9680. return Camera._SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM;
  9681. },
  9682. enumerable: true,
  9683. configurable: true
  9684. });
  9685. Object.defineProperty(Camera, "SUB_CAMERA_MODE_VERTICAL_STEREOGRAM", {
  9686. get: function () {
  9687. return Camera._SUB_CAMERA_MODE_VERTICAL_STEREOGRAM;
  9688. },
  9689. enumerable: true,
  9690. configurable: true
  9691. });
  9692. Object.defineProperty(Camera, "SUB_CAMERA_MODE_VR", {
  9693. get: function () {
  9694. return Camera._SUB_CAMERA_MODE_VR;
  9695. },
  9696. enumerable: true,
  9697. configurable: true
  9698. });
  9699. Object.defineProperty(Camera, "SUB_CAMERAID_A", {
  9700. get: function () {
  9701. return Camera._SUB_CAMERAID_A;
  9702. },
  9703. enumerable: true,
  9704. configurable: true
  9705. });
  9706. Object.defineProperty(Camera, "SUB_CAMERAID_B", {
  9707. get: function () {
  9708. return Camera._SUB_CAMERAID_B;
  9709. },
  9710. enumerable: true,
  9711. configurable: true
  9712. });
  9713. Object.defineProperty(Camera.prototype, "globalPosition", {
  9714. get: function () {
  9715. return this._globalPosition;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Camera.prototype.getActiveMeshes = function () {
  9721. return this._activeMeshes;
  9722. };
  9723. Camera.prototype.isActiveMesh = function (mesh) {
  9724. return (this._activeMeshes.indexOf(mesh) !== -1);
  9725. };
  9726. //Cache
  9727. Camera.prototype._initCache = function () {
  9728. _super.prototype._initCache.call(this);
  9729. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9730. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9731. this._cache.mode = undefined;
  9732. this._cache.minZ = undefined;
  9733. this._cache.maxZ = undefined;
  9734. this._cache.fov = undefined;
  9735. this._cache.aspectRatio = undefined;
  9736. this._cache.orthoLeft = undefined;
  9737. this._cache.orthoRight = undefined;
  9738. this._cache.orthoBottom = undefined;
  9739. this._cache.orthoTop = undefined;
  9740. this._cache.renderWidth = undefined;
  9741. this._cache.renderHeight = undefined;
  9742. };
  9743. Camera.prototype._updateCache = function (ignoreParentClass) {
  9744. if (!ignoreParentClass) {
  9745. _super.prototype._updateCache.call(this);
  9746. }
  9747. var engine = this.getEngine();
  9748. this._cache.position.copyFrom(this.position);
  9749. this._cache.upVector.copyFrom(this.upVector);
  9750. this._cache.mode = this.mode;
  9751. this._cache.minZ = this.minZ;
  9752. this._cache.maxZ = this.maxZ;
  9753. this._cache.fov = this.fov;
  9754. this._cache.aspectRatio = engine.getAspectRatio(this);
  9755. this._cache.orthoLeft = this.orthoLeft;
  9756. this._cache.orthoRight = this.orthoRight;
  9757. this._cache.orthoBottom = this.orthoBottom;
  9758. this._cache.orthoTop = this.orthoTop;
  9759. this._cache.renderWidth = engine.getRenderWidth();
  9760. this._cache.renderHeight = engine.getRenderHeight();
  9761. };
  9762. Camera.prototype._updateFromScene = function () {
  9763. this.updateCache();
  9764. this._update();
  9765. };
  9766. // Synchronized
  9767. Camera.prototype._isSynchronized = function () {
  9768. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9769. };
  9770. Camera.prototype._isSynchronizedViewMatrix = function () {
  9771. if (!_super.prototype._isSynchronized.call(this))
  9772. return false;
  9773. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  9774. };
  9775. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9776. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  9777. if (!check) {
  9778. return false;
  9779. }
  9780. var engine = this.getEngine();
  9781. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9782. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  9783. }
  9784. else {
  9785. check = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === engine.getRenderWidth() && this._cache.renderHeight === engine.getRenderHeight();
  9786. }
  9787. return check;
  9788. };
  9789. // Controls
  9790. Camera.prototype.attachControl = function (element) {
  9791. };
  9792. Camera.prototype.detachControl = function (element) {
  9793. };
  9794. Camera.prototype._update = function () {
  9795. this._checkInputs();
  9796. if (this._subCameraMode !== Camera.SUB_CAMERA_MODE_NONE) {
  9797. this._updateSubCameras();
  9798. }
  9799. };
  9800. Camera.prototype._checkInputs = function () {
  9801. };
  9802. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9803. if (insertAt === void 0) { insertAt = null; }
  9804. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9805. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9806. return 0;
  9807. }
  9808. if (insertAt == null || insertAt < 0) {
  9809. this._postProcesses.push(postProcess);
  9810. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9811. return this._postProcesses.length - 1;
  9812. }
  9813. var add = 0;
  9814. if (this._postProcesses[insertAt]) {
  9815. var start = this._postProcesses.length - 1;
  9816. for (var i = start; i >= insertAt + 1; --i) {
  9817. this._postProcesses[i + 1] = this._postProcesses[i];
  9818. }
  9819. add = 1;
  9820. }
  9821. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9822. if (this._postProcessesTakenIndices[i] < insertAt) {
  9823. continue;
  9824. }
  9825. start = this._postProcessesTakenIndices.length - 1;
  9826. for (var j = start; j >= i; --j) {
  9827. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9828. }
  9829. this._postProcessesTakenIndices[i] = insertAt;
  9830. break;
  9831. }
  9832. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  9833. this._postProcessesTakenIndices.push(insertAt);
  9834. }
  9835. var result = insertAt + add;
  9836. this._postProcesses[result] = postProcess;
  9837. return result;
  9838. };
  9839. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9840. if (atIndices === void 0) { atIndices = null; }
  9841. var result = [];
  9842. if (!atIndices) {
  9843. var length = this._postProcesses.length;
  9844. for (var i = 0; i < length; i++) {
  9845. if (this._postProcesses[i] !== postProcess) {
  9846. continue;
  9847. }
  9848. delete this._postProcesses[i];
  9849. var index = this._postProcessesTakenIndices.indexOf(i);
  9850. this._postProcessesTakenIndices.splice(index, 1);
  9851. }
  9852. }
  9853. else {
  9854. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9855. for (i = 0; i < atIndices.length; i++) {
  9856. var foundPostProcess = this._postProcesses[atIndices[i]];
  9857. if (foundPostProcess !== postProcess) {
  9858. result.push(i);
  9859. continue;
  9860. }
  9861. delete this._postProcesses[atIndices[i]];
  9862. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9863. this._postProcessesTakenIndices.splice(index, 1);
  9864. }
  9865. }
  9866. return result;
  9867. };
  9868. Camera.prototype.getWorldMatrix = function () {
  9869. if (!this._worldMatrix) {
  9870. this._worldMatrix = BABYLON.Matrix.Identity();
  9871. }
  9872. var viewMatrix = this.getViewMatrix();
  9873. viewMatrix.invertToRef(this._worldMatrix);
  9874. return this._worldMatrix;
  9875. };
  9876. Camera.prototype._getViewMatrix = function () {
  9877. return BABYLON.Matrix.Identity();
  9878. };
  9879. Camera.prototype.getViewMatrix = function (force) {
  9880. this._computedViewMatrix = this._computeViewMatrix(force);
  9881. if (!force && this._isSynchronizedViewMatrix()) {
  9882. return this._computedViewMatrix;
  9883. }
  9884. if (!this.parent || !this.parent.getWorldMatrix) {
  9885. this._globalPosition.copyFrom(this.position);
  9886. }
  9887. else {
  9888. if (!this._worldMatrix) {
  9889. this._worldMatrix = BABYLON.Matrix.Identity();
  9890. }
  9891. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9892. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9893. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9894. this._computedViewMatrix.invert();
  9895. this._markSyncedWithParent();
  9896. }
  9897. this._currentRenderId = this.getScene().getRenderId();
  9898. return this._computedViewMatrix;
  9899. };
  9900. Camera.prototype._computeViewMatrix = function (force) {
  9901. if (!force && this._isSynchronizedViewMatrix()) {
  9902. return this._computedViewMatrix;
  9903. }
  9904. this._computedViewMatrix = this._getViewMatrix();
  9905. this._currentRenderId = this.getScene().getRenderId();
  9906. return this._computedViewMatrix;
  9907. };
  9908. Camera.prototype.getProjectionMatrix = function (force) {
  9909. if (!force && this._isSynchronizedProjectionMatrix()) {
  9910. return this._projectionMatrix;
  9911. }
  9912. var engine = this.getEngine();
  9913. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9914. if (this.minZ <= 0) {
  9915. this.minZ = 0.1;
  9916. }
  9917. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9918. return this._projectionMatrix;
  9919. }
  9920. var halfWidth = engine.getRenderWidth() / 2.0;
  9921. var halfHeight = engine.getRenderHeight() / 2.0;
  9922. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9923. return this._projectionMatrix;
  9924. };
  9925. Camera.prototype.dispose = function () {
  9926. // Remove from scene
  9927. this.getScene().removeCamera(this);
  9928. while (this.subCameras.length > 0) {
  9929. this.subCameras.pop().dispose();
  9930. }
  9931. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9932. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9933. }
  9934. };
  9935. // ---- 3D cameras section ----
  9936. Camera.prototype.setSubCameraMode = function (mode, halfSpace, metrics) {
  9937. if (halfSpace === void 0) { halfSpace = 0; }
  9938. while (this.subCameras.length > 0) {
  9939. this.subCameras.pop().dispose();
  9940. }
  9941. this._subCameraMode = mode;
  9942. this._subCamHalfSpace = BABYLON.Tools.ToRadians(halfSpace);
  9943. var camA = this.getSubCamera(this.name + "_A", true);
  9944. var camB = this.getSubCamera(this.name + "_B", false);
  9945. var postProcessA;
  9946. var postProcessB;
  9947. switch (this._subCameraMode) {
  9948. case Camera.SUB_CAMERA_MODE_ANAGLYPH:
  9949. postProcessA = new BABYLON.PassPostProcess(this.name + "_leftTexture", 1.0, camA);
  9950. camA.isIntermediate = true;
  9951. postProcessB = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, camB);
  9952. postProcessB.onApply = function (effect) {
  9953. effect.setTextureFromPostProcess("leftSampler", postProcessA);
  9954. };
  9955. break;
  9956. case Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM:
  9957. case Camera.SUB_CAMERA_MODE_VERTICAL_STEREOGRAM:
  9958. var isStereogramHoriz = this._subCameraMode === Camera.SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM;
  9959. postProcessA = new BABYLON.PassPostProcess("passthru", 1.0, camA);
  9960. camA.isIntermediate = true;
  9961. postProcessB = new BABYLON.StereogramInterlacePostProcess("st_interlace", camB, postProcessA, isStereogramHoriz);
  9962. break;
  9963. case Camera.SUB_CAMERA_MODE_VR:
  9964. metrics = metrics || VRCameraMetrics.GetDefault();
  9965. ;
  9966. camA._vrMetrics = metrics;
  9967. camA.viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  9968. camA._vrWorkMatrix = new BABYLON.Matrix();
  9969. camA._vrHMatrix = metrics.leftHMatrix;
  9970. camA._vrPreViewMatrix = metrics.leftPreViewMatrix;
  9971. camA.getProjectionMatrix = camA._getVRProjectionMatrix;
  9972. if (metrics.compensateDistorsion) {
  9973. postProcessA = new BABYLON.VRDistortionCorrectionPostProcess("Distortion Compensation Left", camA, false, metrics);
  9974. }
  9975. camB._vrMetrics = camA._vrMetrics;
  9976. camB.viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  9977. camB._vrWorkMatrix = new BABYLON.Matrix();
  9978. camB._vrHMatrix = metrics.rightHMatrix;
  9979. camB._vrPreViewMatrix = metrics.rightPreViewMatrix;
  9980. camB.getProjectionMatrix = camB._getVRProjectionMatrix;
  9981. if (metrics.compensateDistorsion) {
  9982. postProcessB = new BABYLON.VRDistortionCorrectionPostProcess("Distortion Compensation Right", camB, true, metrics);
  9983. }
  9984. }
  9985. if (this._subCameraMode !== Camera.SUB_CAMERA_MODE_NONE) {
  9986. this.subCameras.push(camA);
  9987. this.subCameras.push(camB);
  9988. }
  9989. this._update();
  9990. };
  9991. Camera.prototype._getVRProjectionMatrix = function () {
  9992. BABYLON.Matrix.PerspectiveFovLHToRef(this._vrMetrics.aspectRatioFov, this._vrMetrics.aspectRatio, this.minZ, this.maxZ, this._vrWorkMatrix);
  9993. this._vrWorkMatrix.multiplyToRef(this._vrHMatrix, this._projectionMatrix);
  9994. return this._projectionMatrix;
  9995. };
  9996. Camera.prototype.setSubCamHalfSpace = function (halfSpace) {
  9997. this._subCamHalfSpace = BABYLON.Tools.ToRadians(halfSpace);
  9998. };
  9999. /**
  10000. * May needs to be overridden by children so sub has required properties to be copied
  10001. */
  10002. Camera.prototype.getSubCamera = function (name, isA) {
  10003. return null;
  10004. };
  10005. /**
  10006. * May needs to be overridden by children
  10007. */
  10008. Camera.prototype._updateSubCameras = function () {
  10009. var camA = this.subCameras[Camera.SUB_CAMERAID_A];
  10010. var camB = this.subCameras[Camera.SUB_CAMERAID_B];
  10011. camA.minZ = camB.minZ = this.minZ;
  10012. camA.maxZ = camB.maxZ = this.maxZ;
  10013. camA.fov = camB.fov = this.fov;
  10014. // only update viewport, when ANAGLYPH
  10015. if (this._subCameraMode === Camera.SUB_CAMERA_MODE_ANAGLYPH) {
  10016. camA.viewport = camB.viewport = this.viewport;
  10017. }
  10018. };
  10019. // Statics
  10020. Camera._PERSPECTIVE_CAMERA = 0;
  10021. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10022. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10023. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10024. Camera._SUB_CAMERA_MODE_NONE = 0;
  10025. Camera._SUB_CAMERA_MODE_ANAGLYPH = 1;
  10026. Camera._SUB_CAMERA_MODE_HORIZONTAL_STEREOGRAM = 2;
  10027. Camera._SUB_CAMERA_MODE_VERTICAL_STEREOGRAM = 3;
  10028. Camera._SUB_CAMERA_MODE_VR = 4;
  10029. Camera._SUB_CAMERAID_A = 0;
  10030. Camera._SUB_CAMERAID_B = 1;
  10031. return Camera;
  10032. })(BABYLON.Node);
  10033. BABYLON.Camera = Camera;
  10034. })(BABYLON || (BABYLON = {}));
  10035. //# sourceMappingURL=babylon.camera.js.map
  10036. var __extends = this.__extends || function (d, b) {
  10037. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10038. function __() { this.constructor = d; }
  10039. __.prototype = b.prototype;
  10040. d.prototype = new __();
  10041. };
  10042. var BABYLON;
  10043. (function (BABYLON) {
  10044. var TargetCamera = (function (_super) {
  10045. __extends(TargetCamera, _super);
  10046. function TargetCamera(name, position, scene) {
  10047. _super.call(this, name, position, scene);
  10048. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10049. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10050. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10051. this.speed = 2.0;
  10052. this.noRotationConstraint = false;
  10053. this.lockedTarget = null;
  10054. this._currentTarget = BABYLON.Vector3.Zero();
  10055. this._viewMatrix = BABYLON.Matrix.Zero();
  10056. this._camMatrix = BABYLON.Matrix.Zero();
  10057. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10058. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10059. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10060. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10061. this._lookAtTemp = BABYLON.Matrix.Zero();
  10062. this._tempMatrix = BABYLON.Matrix.Zero();
  10063. }
  10064. TargetCamera.prototype._getLockedTargetPosition = function () {
  10065. if (!this.lockedTarget) {
  10066. return null;
  10067. }
  10068. return this.lockedTarget.position || this.lockedTarget;
  10069. };
  10070. // Cache
  10071. TargetCamera.prototype._initCache = function () {
  10072. _super.prototype._initCache.call(this);
  10073. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10074. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10075. };
  10076. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10077. if (!ignoreParentClass) {
  10078. _super.prototype._updateCache.call(this);
  10079. }
  10080. var lockedTargetPosition = this._getLockedTargetPosition();
  10081. if (!lockedTargetPosition) {
  10082. this._cache.lockedTarget = null;
  10083. }
  10084. else {
  10085. if (!this._cache.lockedTarget) {
  10086. this._cache.lockedTarget = lockedTargetPosition.clone();
  10087. }
  10088. else {
  10089. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10090. }
  10091. }
  10092. this._cache.rotation.copyFrom(this.rotation);
  10093. };
  10094. // Synchronized
  10095. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10096. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10097. return false;
  10098. }
  10099. var lockedTargetPosition = this._getLockedTargetPosition();
  10100. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  10101. };
  10102. // Methods
  10103. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10104. var engine = this.getEngine();
  10105. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10106. };
  10107. // Target
  10108. TargetCamera.prototype.setTarget = function (target) {
  10109. this.upVector.normalize();
  10110. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10111. this._camMatrix.invert();
  10112. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10113. var vDir = target.subtract(this.position);
  10114. if (vDir.x >= 0.0) {
  10115. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10116. }
  10117. else {
  10118. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10119. }
  10120. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10121. if (isNaN(this.rotation.x)) {
  10122. this.rotation.x = 0;
  10123. }
  10124. if (isNaN(this.rotation.y)) {
  10125. this.rotation.y = 0;
  10126. }
  10127. if (isNaN(this.rotation.z)) {
  10128. this.rotation.z = 0;
  10129. }
  10130. };
  10131. TargetCamera.prototype.getTarget = function () {
  10132. return this._currentTarget;
  10133. };
  10134. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10135. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10136. };
  10137. TargetCamera.prototype._updatePosition = function () {
  10138. this.position.addInPlace(this.cameraDirection);
  10139. };
  10140. TargetCamera.prototype._checkInputs = function () {
  10141. var needToMove = this._decideIfNeedsToMove();
  10142. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10143. // Move
  10144. if (needToMove) {
  10145. this._updatePosition();
  10146. }
  10147. // Rotate
  10148. if (needToRotate) {
  10149. this.rotation.x += this.cameraRotation.x;
  10150. this.rotation.y += this.cameraRotation.y;
  10151. if (!this.noRotationConstraint) {
  10152. var limit = (Math.PI / 2) * 0.95;
  10153. if (this.rotation.x > limit)
  10154. this.rotation.x = limit;
  10155. if (this.rotation.x < -limit)
  10156. this.rotation.x = -limit;
  10157. }
  10158. }
  10159. // Inertia
  10160. if (needToMove) {
  10161. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10162. this.cameraDirection.x = 0;
  10163. }
  10164. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10165. this.cameraDirection.y = 0;
  10166. }
  10167. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10168. this.cameraDirection.z = 0;
  10169. }
  10170. this.cameraDirection.scaleInPlace(this.inertia);
  10171. }
  10172. if (needToRotate) {
  10173. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10174. this.cameraRotation.x = 0;
  10175. }
  10176. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10177. this.cameraRotation.y = 0;
  10178. }
  10179. this.cameraRotation.scaleInPlace(this.inertia);
  10180. }
  10181. _super.prototype._checkInputs.call(this);
  10182. };
  10183. TargetCamera.prototype._getViewMatrix = function () {
  10184. if (!this.lockedTarget) {
  10185. // Compute
  10186. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10187. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10188. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10189. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10190. this._lookAtTemp.invert();
  10191. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10192. }
  10193. else {
  10194. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10195. }
  10196. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10197. // Computing target and final matrix
  10198. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10199. }
  10200. else {
  10201. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10202. }
  10203. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10204. return this._viewMatrix;
  10205. };
  10206. TargetCamera.prototype._getVRViewMatrix = function () {
  10207. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10208. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10209. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._vrActualUp);
  10210. // Computing target and final matrix
  10211. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10212. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._vrActualUp, this._vrWorkMatrix);
  10213. this._vrWorkMatrix.multiplyToRef(this._vrPreViewMatrix, this._viewMatrix);
  10214. return this._viewMatrix;
  10215. };
  10216. /**
  10217. * @override
  10218. * needs to be overridden, so sub has required properties to be copied
  10219. */
  10220. TargetCamera.prototype.getSubCamera = function (name, isA) {
  10221. var subCamera = new BABYLON.TargetCamera(name, this.position.clone(), this.getScene());
  10222. if (this._subCameraMode === BABYLON.Camera.SUB_CAMERA_MODE_VR) {
  10223. subCamera._vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10224. subCamera._getViewMatrix = subCamera._getVRViewMatrix;
  10225. }
  10226. return subCamera;
  10227. };
  10228. /**
  10229. * @override
  10230. * needs to be overridden, adding copy of position, and rotation for VR, or target for rest
  10231. */
  10232. TargetCamera.prototype._updateSubCameras = function () {
  10233. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  10234. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  10235. if (this._subCameraMode === BABYLON.Camera.SUB_CAMERA_MODE_VR) {
  10236. camA.rotation.x = camB.rotation.x = this.rotation.x;
  10237. camA.rotation.y = camB.rotation.y = this.rotation.y;
  10238. camA.rotation.z = camB.rotation.z = this.rotation.z;
  10239. camA.position.copyFrom(this.position);
  10240. camB.position.copyFrom(this.position);
  10241. }
  10242. else {
  10243. camA.setTarget(this.getTarget());
  10244. camB.setTarget(this.getTarget());
  10245. this._getSubCamPosition(-this._subCamHalfSpace, camA.position);
  10246. this._getSubCamPosition(this._subCamHalfSpace, camB.position);
  10247. }
  10248. _super.prototype._updateSubCameras.call(this);
  10249. };
  10250. TargetCamera.prototype._getSubCamPosition = function (halfSpace, result) {
  10251. if (!this._subCamTransformMatrix) {
  10252. this._subCamTransformMatrix = new BABYLON.Matrix();
  10253. }
  10254. var target = this.getTarget();
  10255. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._subCamTransformMatrix);
  10256. this._subCamTransformMatrix = this._subCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10257. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._subCamTransformMatrix, result);
  10258. };
  10259. return TargetCamera;
  10260. })(BABYLON.Camera);
  10261. BABYLON.TargetCamera = TargetCamera;
  10262. })(BABYLON || (BABYLON = {}));
  10263. //# sourceMappingURL=babylon.targetCamera.js.map
  10264. var __extends = this.__extends || function (d, b) {
  10265. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10266. function __() { this.constructor = d; }
  10267. __.prototype = b.prototype;
  10268. d.prototype = new __();
  10269. };
  10270. var BABYLON;
  10271. (function (BABYLON) {
  10272. var FreeCamera = (function (_super) {
  10273. __extends(FreeCamera, _super);
  10274. function FreeCamera(name, position, scene) {
  10275. var _this = this;
  10276. _super.call(this, name, position, scene);
  10277. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10278. this.keysUp = [38];
  10279. this.keysDown = [40];
  10280. this.keysLeft = [37];
  10281. this.keysRight = [39];
  10282. this.checkCollisions = false;
  10283. this.applyGravity = false;
  10284. this.angularSensibility = 2000.0;
  10285. this._keys = [];
  10286. this._collider = new BABYLON.Collider();
  10287. this._needMoveForGravity = false;
  10288. this._oldPosition = BABYLON.Vector3.Zero();
  10289. this._diffPosition = BABYLON.Vector3.Zero();
  10290. this._newPosition = BABYLON.Vector3.Zero();
  10291. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10292. if (collidedMesh === void 0) { collidedMesh = null; }
  10293. //TODO move this to the collision coordinator!
  10294. if (_this.getScene().workerCollisions)
  10295. newPosition.multiplyInPlace(_this._collider.radius);
  10296. var updatePosition = function (newPos) {
  10297. _this._newPosition.copyFrom(newPos);
  10298. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10299. var oldPosition = _this.position.clone();
  10300. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10301. _this.position.addInPlace(_this._diffPosition);
  10302. if (_this.onCollide && collidedMesh) {
  10303. _this.onCollide(collidedMesh);
  10304. }
  10305. }
  10306. };
  10307. updatePosition(newPosition);
  10308. };
  10309. }
  10310. // Controls
  10311. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10312. var _this = this;
  10313. var previousPosition;
  10314. var engine = this.getEngine();
  10315. if (this._attachedElement) {
  10316. return;
  10317. }
  10318. this._attachedElement = element;
  10319. if (this._onMouseDown === undefined) {
  10320. this._onMouseDown = function (evt) {
  10321. previousPosition = {
  10322. x: evt.clientX,
  10323. y: evt.clientY
  10324. };
  10325. if (!noPreventDefault) {
  10326. evt.preventDefault();
  10327. }
  10328. };
  10329. this._onMouseUp = function (evt) {
  10330. previousPosition = null;
  10331. if (!noPreventDefault) {
  10332. evt.preventDefault();
  10333. }
  10334. };
  10335. this._onMouseOut = function (evt) {
  10336. previousPosition = null;
  10337. _this._keys = [];
  10338. if (!noPreventDefault) {
  10339. evt.preventDefault();
  10340. }
  10341. };
  10342. this._onMouseMove = function (evt) {
  10343. if (!previousPosition && !engine.isPointerLock) {
  10344. return;
  10345. }
  10346. var offsetX;
  10347. var offsetY;
  10348. if (!engine.isPointerLock) {
  10349. offsetX = evt.clientX - previousPosition.x;
  10350. offsetY = evt.clientY - previousPosition.y;
  10351. }
  10352. else {
  10353. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10354. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10355. }
  10356. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10357. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10358. previousPosition = {
  10359. x: evt.clientX,
  10360. y: evt.clientY
  10361. };
  10362. if (!noPreventDefault) {
  10363. evt.preventDefault();
  10364. }
  10365. };
  10366. this._onKeyDown = function (evt) {
  10367. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10368. var index = _this._keys.indexOf(evt.keyCode);
  10369. if (index === -1) {
  10370. _this._keys.push(evt.keyCode);
  10371. }
  10372. if (!noPreventDefault) {
  10373. evt.preventDefault();
  10374. }
  10375. }
  10376. };
  10377. this._onKeyUp = function (evt) {
  10378. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10379. var index = _this._keys.indexOf(evt.keyCode);
  10380. if (index >= 0) {
  10381. _this._keys.splice(index, 1);
  10382. }
  10383. if (!noPreventDefault) {
  10384. evt.preventDefault();
  10385. }
  10386. }
  10387. };
  10388. this._onLostFocus = function () {
  10389. _this._keys = [];
  10390. };
  10391. this._reset = function () {
  10392. _this._keys = [];
  10393. previousPosition = null;
  10394. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10395. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10396. };
  10397. }
  10398. element.addEventListener("mousedown", this._onMouseDown, false);
  10399. element.addEventListener("mouseup", this._onMouseUp, false);
  10400. element.addEventListener("mouseout", this._onMouseOut, false);
  10401. element.addEventListener("mousemove", this._onMouseMove, false);
  10402. BABYLON.Tools.RegisterTopRootEvents([
  10403. { name: "keydown", handler: this._onKeyDown },
  10404. { name: "keyup", handler: this._onKeyUp },
  10405. { name: "blur", handler: this._onLostFocus }
  10406. ]);
  10407. };
  10408. FreeCamera.prototype.detachControl = function (element) {
  10409. if (this._attachedElement != element) {
  10410. return;
  10411. }
  10412. element.removeEventListener("mousedown", this._onMouseDown);
  10413. element.removeEventListener("mouseup", this._onMouseUp);
  10414. element.removeEventListener("mouseout", this._onMouseOut);
  10415. element.removeEventListener("mousemove", this._onMouseMove);
  10416. BABYLON.Tools.UnregisterTopRootEvents([
  10417. { name: "keydown", handler: this._onKeyDown },
  10418. { name: "keyup", handler: this._onKeyUp },
  10419. { name: "blur", handler: this._onLostFocus }
  10420. ]);
  10421. this._attachedElement = null;
  10422. if (this._reset) {
  10423. this._reset();
  10424. }
  10425. };
  10426. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10427. var globalPosition;
  10428. if (this.parent) {
  10429. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10430. }
  10431. else {
  10432. globalPosition = this.position;
  10433. }
  10434. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10435. this._collider.radius = this.ellipsoid;
  10436. //add gravity to the velocity to prevent the dual-collision checking
  10437. if (this.applyGravity) {
  10438. velocity.addInPlace(this.getScene().gravity);
  10439. }
  10440. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10441. };
  10442. FreeCamera.prototype._checkInputs = function () {
  10443. if (!this._localDirection) {
  10444. this._localDirection = BABYLON.Vector3.Zero();
  10445. this._transformedDirection = BABYLON.Vector3.Zero();
  10446. }
  10447. for (var index = 0; index < this._keys.length; index++) {
  10448. var keyCode = this._keys[index];
  10449. var speed = this._computeLocalCameraSpeed();
  10450. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10451. this._localDirection.copyFromFloats(-speed, 0, 0);
  10452. }
  10453. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10454. this._localDirection.copyFromFloats(0, 0, speed);
  10455. }
  10456. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10457. this._localDirection.copyFromFloats(speed, 0, 0);
  10458. }
  10459. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10460. this._localDirection.copyFromFloats(0, 0, -speed);
  10461. }
  10462. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10463. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10464. this.cameraDirection.addInPlace(this._transformedDirection);
  10465. }
  10466. _super.prototype._checkInputs.call(this);
  10467. };
  10468. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10469. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10470. };
  10471. FreeCamera.prototype._updatePosition = function () {
  10472. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10473. this._collideWithWorld(this.cameraDirection);
  10474. }
  10475. else {
  10476. this.position.addInPlace(this.cameraDirection);
  10477. }
  10478. };
  10479. return FreeCamera;
  10480. })(BABYLON.TargetCamera);
  10481. BABYLON.FreeCamera = FreeCamera;
  10482. })(BABYLON || (BABYLON = {}));
  10483. //# sourceMappingURL=babylon.freeCamera.js.map
  10484. var __extends = this.__extends || function (d, b) {
  10485. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10486. function __() { this.constructor = d; }
  10487. __.prototype = b.prototype;
  10488. d.prototype = new __();
  10489. };
  10490. var BABYLON;
  10491. (function (BABYLON) {
  10492. var FollowCamera = (function (_super) {
  10493. __extends(FollowCamera, _super);
  10494. function FollowCamera(name, position, scene) {
  10495. _super.call(this, name, position, scene);
  10496. this.radius = 12;
  10497. this.rotationOffset = 0;
  10498. this.heightOffset = 4;
  10499. this.cameraAcceleration = 0.05;
  10500. this.maxCameraSpeed = 20;
  10501. }
  10502. FollowCamera.prototype.getRadians = function (degrees) {
  10503. return degrees * Math.PI / 180;
  10504. };
  10505. FollowCamera.prototype.follow = function (cameraTarget) {
  10506. if (!cameraTarget)
  10507. return;
  10508. var yRotation;
  10509. if (cameraTarget.rotationQuaternion) {
  10510. var rotMatrix = new BABYLON.Matrix();
  10511. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10512. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10513. }
  10514. else {
  10515. yRotation = cameraTarget.rotation.y;
  10516. }
  10517. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10518. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10519. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10520. var dx = targetX - this.position.x;
  10521. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10522. var dz = (targetZ) - this.position.z;
  10523. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10524. var vy = dy * this.cameraAcceleration;
  10525. var vz = dz * this.cameraAcceleration * 2;
  10526. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10527. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10528. }
  10529. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10530. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10531. }
  10532. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10533. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10534. }
  10535. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10536. this.setTarget(cameraTarget.position);
  10537. };
  10538. FollowCamera.prototype._checkInputs = function () {
  10539. _super.prototype._checkInputs.call(this);
  10540. this.follow(this.target);
  10541. };
  10542. return FollowCamera;
  10543. })(BABYLON.TargetCamera);
  10544. BABYLON.FollowCamera = FollowCamera;
  10545. })(BABYLON || (BABYLON = {}));
  10546. //# sourceMappingURL=babylon.followCamera.js.map
  10547. var __extends = this.__extends || function (d, b) {
  10548. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10549. function __() { this.constructor = d; }
  10550. __.prototype = b.prototype;
  10551. d.prototype = new __();
  10552. };
  10553. var BABYLON;
  10554. (function (BABYLON) {
  10555. // We're mainly based on the logic defined into the FreeCamera code
  10556. var TouchCamera = (function (_super) {
  10557. __extends(TouchCamera, _super);
  10558. function TouchCamera(name, position, scene) {
  10559. _super.call(this, name, position, scene);
  10560. this._offsetX = null;
  10561. this._offsetY = null;
  10562. this._pointerCount = 0;
  10563. this._pointerPressed = [];
  10564. this.angularSensibility = 200000.0;
  10565. this.moveSensibility = 500.0;
  10566. }
  10567. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10568. var _this = this;
  10569. var previousPosition;
  10570. if (this._attachedCanvas) {
  10571. return;
  10572. }
  10573. this._attachedCanvas = canvas;
  10574. if (this._onPointerDown === undefined) {
  10575. this._onPointerDown = function (evt) {
  10576. if (!noPreventDefault) {
  10577. evt.preventDefault();
  10578. }
  10579. _this._pointerPressed.push(evt.pointerId);
  10580. if (_this._pointerPressed.length !== 1) {
  10581. return;
  10582. }
  10583. previousPosition = {
  10584. x: evt.clientX,
  10585. y: evt.clientY
  10586. };
  10587. };
  10588. this._onPointerUp = function (evt) {
  10589. if (!noPreventDefault) {
  10590. evt.preventDefault();
  10591. }
  10592. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10593. if (index === -1) {
  10594. return;
  10595. }
  10596. _this._pointerPressed.splice(index, 1);
  10597. if (index != 0) {
  10598. return;
  10599. }
  10600. previousPosition = null;
  10601. _this._offsetX = null;
  10602. _this._offsetY = null;
  10603. };
  10604. this._onPointerMove = function (evt) {
  10605. if (!noPreventDefault) {
  10606. evt.preventDefault();
  10607. }
  10608. if (!previousPosition) {
  10609. return;
  10610. }
  10611. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10612. if (index != 0) {
  10613. return;
  10614. }
  10615. _this._offsetX = evt.clientX - previousPosition.x;
  10616. _this._offsetY = -(evt.clientY - previousPosition.y);
  10617. };
  10618. this._onLostFocus = function () {
  10619. _this._offsetX = null;
  10620. _this._offsetY = null;
  10621. };
  10622. }
  10623. canvas.addEventListener("pointerdown", this._onPointerDown);
  10624. canvas.addEventListener("pointerup", this._onPointerUp);
  10625. canvas.addEventListener("pointerout", this._onPointerUp);
  10626. canvas.addEventListener("pointermove", this._onPointerMove);
  10627. BABYLON.Tools.RegisterTopRootEvents([
  10628. { name: "blur", handler: this._onLostFocus }
  10629. ]);
  10630. };
  10631. TouchCamera.prototype.detachControl = function (canvas) {
  10632. if (this._attachedCanvas != canvas) {
  10633. return;
  10634. }
  10635. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10636. canvas.removeEventListener("pointerup", this._onPointerUp);
  10637. canvas.removeEventListener("pointerout", this._onPointerUp);
  10638. canvas.removeEventListener("pointermove", this._onPointerMove);
  10639. BABYLON.Tools.UnregisterTopRootEvents([
  10640. { name: "blur", handler: this._onLostFocus }
  10641. ]);
  10642. this._attachedCanvas = null;
  10643. };
  10644. TouchCamera.prototype._checkInputs = function () {
  10645. if (!this._offsetX) {
  10646. return;
  10647. }
  10648. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10649. if (this._pointerPressed.length > 1) {
  10650. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10651. }
  10652. else {
  10653. var speed = this._computeLocalCameraSpeed();
  10654. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10655. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10656. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10657. }
  10658. _super.prototype._checkInputs.call(this);
  10659. };
  10660. return TouchCamera;
  10661. })(BABYLON.FreeCamera);
  10662. BABYLON.TouchCamera = TouchCamera;
  10663. })(BABYLON || (BABYLON = {}));
  10664. //# sourceMappingURL=babylon.touchCamera.js.map
  10665. var __extends = this.__extends || function (d, b) {
  10666. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10667. function __() { this.constructor = d; }
  10668. __.prototype = b.prototype;
  10669. d.prototype = new __();
  10670. };
  10671. var BABYLON;
  10672. (function (BABYLON) {
  10673. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10674. var ArcRotateCamera = (function (_super) {
  10675. __extends(ArcRotateCamera, _super);
  10676. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10677. var _this = this;
  10678. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10679. this.alpha = alpha;
  10680. this.beta = beta;
  10681. this.radius = radius;
  10682. this.target = target;
  10683. this.inertialAlphaOffset = 0;
  10684. this.inertialBetaOffset = 0;
  10685. this.inertialRadiusOffset = 0;
  10686. this.lowerAlphaLimit = null;
  10687. this.upperAlphaLimit = null;
  10688. this.lowerBetaLimit = 0.01;
  10689. this.upperBetaLimit = Math.PI;
  10690. this.lowerRadiusLimit = null;
  10691. this.upperRadiusLimit = null;
  10692. this.angularSensibility = 1000.0;
  10693. this.wheelPrecision = 3.0;
  10694. this.pinchPrecision = 2.0;
  10695. this.keysUp = [38];
  10696. this.keysDown = [40];
  10697. this.keysLeft = [37];
  10698. this.keysRight = [39];
  10699. this.zoomOnFactor = 1;
  10700. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10701. this.pinchInwards = true;
  10702. this._keys = [];
  10703. this._viewMatrix = new BABYLON.Matrix();
  10704. this.checkCollisions = false;
  10705. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10706. this._collider = new BABYLON.Collider();
  10707. this._previousPosition = BABYLON.Vector3.Zero();
  10708. this._collisionVelocity = BABYLON.Vector3.Zero();
  10709. this._newPosition = BABYLON.Vector3.Zero();
  10710. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10711. if (collidedMesh === void 0) { collidedMesh = null; }
  10712. if (collisionId != null || collisionId != undefined)
  10713. newPosition.multiplyInPlace(_this._collider.radius);
  10714. if (!newPosition.equalsWithEpsilon(_this.position)) {
  10715. _this.position.copyFrom(_this._previousPosition);
  10716. _this.alpha = _this._previousAlpha;
  10717. _this.beta = _this._previousBeta;
  10718. _this.radius = _this._previousRadius;
  10719. if (_this.onCollide && collidedMesh) {
  10720. _this.onCollide(collidedMesh);
  10721. }
  10722. }
  10723. _this._collisionTriggered = false;
  10724. };
  10725. if (!this.target) {
  10726. this.target = BABYLON.Vector3.Zero();
  10727. }
  10728. this.getViewMatrix();
  10729. }
  10730. ArcRotateCamera.prototype._getTargetPosition = function () {
  10731. return this.target.position || this.target;
  10732. };
  10733. // Cache
  10734. ArcRotateCamera.prototype._initCache = function () {
  10735. _super.prototype._initCache.call(this);
  10736. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10737. this._cache.alpha = undefined;
  10738. this._cache.beta = undefined;
  10739. this._cache.radius = undefined;
  10740. this._cache.targetScreenOffset = undefined;
  10741. };
  10742. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10743. if (!ignoreParentClass) {
  10744. _super.prototype._updateCache.call(this);
  10745. }
  10746. this._cache.target.copyFrom(this._getTargetPosition());
  10747. this._cache.alpha = this.alpha;
  10748. this._cache.beta = this.beta;
  10749. this._cache.radius = this.radius;
  10750. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10751. };
  10752. // Synchronized
  10753. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10754. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10755. return false;
  10756. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10757. };
  10758. // Methods
  10759. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  10760. var _this = this;
  10761. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10762. var previousPinchDistance = 0;
  10763. var pointers = new BABYLON.SmartCollection();
  10764. if (this._attachedElement) {
  10765. return;
  10766. }
  10767. this._attachedElement = element;
  10768. var engine = this.getEngine();
  10769. if (this._onPointerDown === undefined) {
  10770. this._onPointerDown = function (evt) {
  10771. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10772. cacheSoloPointer = pointers.item(evt.pointerId);
  10773. if (!noPreventDefault) {
  10774. evt.preventDefault();
  10775. }
  10776. };
  10777. this._onPointerUp = function (evt) {
  10778. cacheSoloPointer = null;
  10779. previousPinchDistance = 0;
  10780. pointers.remove(evt.pointerId);
  10781. if (!noPreventDefault) {
  10782. evt.preventDefault();
  10783. }
  10784. };
  10785. this._onPointerMove = function (evt) {
  10786. if (!noPreventDefault) {
  10787. evt.preventDefault();
  10788. }
  10789. switch (pointers.count) {
  10790. case 1:
  10791. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  10792. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  10793. var offsetX = evt.clientX - cacheSoloPointer.x;
  10794. var offsetY = evt.clientY - cacheSoloPointer.y;
  10795. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10796. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10797. //pointers.item(evt.pointerId).x = evt.clientX;
  10798. //pointers.item(evt.pointerId).y = evt.clientY;
  10799. cacheSoloPointer.x = evt.clientX;
  10800. cacheSoloPointer.y = evt.clientY;
  10801. break;
  10802. case 2:
  10803. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10804. pointers.item(evt.pointerId).x = evt.clientX;
  10805. pointers.item(evt.pointerId).y = evt.clientY;
  10806. var direction = _this.pinchInwards ? 1 : -1;
  10807. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10808. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10809. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10810. if (previousPinchDistance === 0) {
  10811. previousPinchDistance = pinchSquaredDistance;
  10812. return;
  10813. }
  10814. if (pinchSquaredDistance !== previousPinchDistance) {
  10815. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  10816. previousPinchDistance = pinchSquaredDistance;
  10817. }
  10818. break;
  10819. default:
  10820. if (pointers.item(evt.pointerId)) {
  10821. pointers.item(evt.pointerId).x = evt.clientX;
  10822. pointers.item(evt.pointerId).y = evt.clientY;
  10823. }
  10824. }
  10825. };
  10826. this._onMouseMove = function (evt) {
  10827. if (!engine.isPointerLock) {
  10828. return;
  10829. }
  10830. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10831. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10832. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10833. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10834. if (!noPreventDefault) {
  10835. evt.preventDefault();
  10836. }
  10837. };
  10838. this._wheel = function (event) {
  10839. var delta = 0;
  10840. if (event.wheelDelta) {
  10841. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10842. }
  10843. else if (event.detail) {
  10844. delta = -event.detail / _this.wheelPrecision;
  10845. }
  10846. if (delta)
  10847. _this.inertialRadiusOffset += delta;
  10848. if (event.preventDefault) {
  10849. if (!noPreventDefault) {
  10850. event.preventDefault();
  10851. }
  10852. }
  10853. };
  10854. this._onKeyDown = function (evt) {
  10855. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10856. var index = _this._keys.indexOf(evt.keyCode);
  10857. if (index === -1) {
  10858. _this._keys.push(evt.keyCode);
  10859. }
  10860. if (evt.preventDefault) {
  10861. if (!noPreventDefault) {
  10862. evt.preventDefault();
  10863. }
  10864. }
  10865. }
  10866. };
  10867. this._onKeyUp = function (evt) {
  10868. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10869. var index = _this._keys.indexOf(evt.keyCode);
  10870. if (index >= 0) {
  10871. _this._keys.splice(index, 1);
  10872. }
  10873. if (evt.preventDefault) {
  10874. if (!noPreventDefault) {
  10875. evt.preventDefault();
  10876. }
  10877. }
  10878. }
  10879. };
  10880. this._onLostFocus = function () {
  10881. _this._keys = [];
  10882. pointers.empty();
  10883. previousPinchDistance = 0;
  10884. cacheSoloPointer = null;
  10885. };
  10886. this._onGestureStart = function (e) {
  10887. if (window.MSGesture === undefined) {
  10888. return;
  10889. }
  10890. if (!_this._MSGestureHandler) {
  10891. _this._MSGestureHandler = new MSGesture();
  10892. _this._MSGestureHandler.target = element;
  10893. }
  10894. _this._MSGestureHandler.addPointer(e.pointerId);
  10895. };
  10896. this._onGesture = function (e) {
  10897. _this.radius *= e.scale;
  10898. if (e.preventDefault) {
  10899. if (!noPreventDefault) {
  10900. e.stopPropagation();
  10901. e.preventDefault();
  10902. }
  10903. }
  10904. };
  10905. this._reset = function () {
  10906. _this._keys = [];
  10907. _this.inertialAlphaOffset = 0;
  10908. _this.inertialBetaOffset = 0;
  10909. _this.inertialRadiusOffset = 0;
  10910. pointers.empty();
  10911. previousPinchDistance = 0;
  10912. cacheSoloPointer = null;
  10913. };
  10914. }
  10915. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10916. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10917. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10918. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10919. element.addEventListener("mousemove", this._onMouseMove, false);
  10920. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10921. element.addEventListener("MSGestureChange", this._onGesture, false);
  10922. element.addEventListener('mousewheel', this._wheel, false);
  10923. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10924. BABYLON.Tools.RegisterTopRootEvents([
  10925. { name: "keydown", handler: this._onKeyDown },
  10926. { name: "keyup", handler: this._onKeyUp },
  10927. { name: "blur", handler: this._onLostFocus }
  10928. ]);
  10929. };
  10930. ArcRotateCamera.prototype.detachControl = function (element) {
  10931. if (this._attachedElement !== element) {
  10932. return;
  10933. }
  10934. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  10935. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  10936. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  10937. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  10938. element.removeEventListener("mousemove", this._onMouseMove);
  10939. element.removeEventListener("MSPointerDown", this._onGestureStart);
  10940. element.removeEventListener("MSGestureChange", this._onGesture);
  10941. element.removeEventListener('mousewheel', this._wheel);
  10942. element.removeEventListener('DOMMouseScroll', this._wheel);
  10943. BABYLON.Tools.UnregisterTopRootEvents([
  10944. { name: "keydown", handler: this._onKeyDown },
  10945. { name: "keyup", handler: this._onKeyUp },
  10946. { name: "blur", handler: this._onLostFocus }
  10947. ]);
  10948. this._MSGestureHandler = null;
  10949. this._attachedElement = null;
  10950. if (this._reset) {
  10951. this._reset();
  10952. }
  10953. };
  10954. ArcRotateCamera.prototype._checkInputs = function () {
  10955. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  10956. if (this._collisionTriggered) {
  10957. return;
  10958. }
  10959. for (var index = 0; index < this._keys.length; index++) {
  10960. var keyCode = this._keys[index];
  10961. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10962. this.inertialAlphaOffset -= 0.01;
  10963. }
  10964. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10965. this.inertialBetaOffset -= 0.01;
  10966. }
  10967. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10968. this.inertialAlphaOffset += 0.01;
  10969. }
  10970. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10971. this.inertialBetaOffset += 0.01;
  10972. }
  10973. }
  10974. // Inertia
  10975. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  10976. this.alpha += this.inertialAlphaOffset;
  10977. this.beta += this.inertialBetaOffset;
  10978. this.radius -= this.inertialRadiusOffset;
  10979. this.inertialAlphaOffset *= this.inertia;
  10980. this.inertialBetaOffset *= this.inertia;
  10981. this.inertialRadiusOffset *= this.inertia;
  10982. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  10983. this.inertialAlphaOffset = 0;
  10984. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  10985. this.inertialBetaOffset = 0;
  10986. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  10987. this.inertialRadiusOffset = 0;
  10988. }
  10989. // Limits
  10990. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  10991. this.alpha = this.lowerAlphaLimit;
  10992. }
  10993. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  10994. this.alpha = this.upperAlphaLimit;
  10995. }
  10996. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  10997. this.beta = this.lowerBetaLimit;
  10998. }
  10999. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  11000. this.beta = this.upperBetaLimit;
  11001. }
  11002. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11003. this.radius = this.lowerRadiusLimit;
  11004. }
  11005. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11006. this.radius = this.upperRadiusLimit;
  11007. }
  11008. _super.prototype._checkInputs.call(this);
  11009. };
  11010. ArcRotateCamera.prototype.setPosition = function (position) {
  11011. var radiusv3 = position.subtract(this._getTargetPosition());
  11012. this.radius = radiusv3.length();
  11013. // Alpha
  11014. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11015. if (radiusv3.z < 0) {
  11016. this.alpha = 2 * Math.PI - this.alpha;
  11017. }
  11018. // Beta
  11019. this.beta = Math.acos(radiusv3.y / this.radius);
  11020. };
  11021. ArcRotateCamera.prototype._getViewMatrix = function () {
  11022. // Compute
  11023. var cosa = Math.cos(this.alpha);
  11024. var sina = Math.sin(this.alpha);
  11025. var cosb = Math.cos(this.beta);
  11026. var sinb = Math.sin(this.beta);
  11027. var target = this._getTargetPosition();
  11028. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  11029. if (this.checkCollisions) {
  11030. this._collider.radius = this.collisionRadius;
  11031. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  11032. this._collisionTriggered = true;
  11033. this.getScene().collisionCoordinator.getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11034. }
  11035. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  11036. this._previousAlpha = this.alpha;
  11037. this._previousBeta = this.beta;
  11038. this._previousRadius = this.radius;
  11039. this._previousPosition.copyFrom(this.position);
  11040. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11041. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11042. return this._viewMatrix;
  11043. };
  11044. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  11045. meshes = meshes || this.getScene().meshes;
  11046. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11047. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11048. this.radius = distance * this.zoomOnFactor;
  11049. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  11050. };
  11051. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  11052. var meshesOrMinMaxVector;
  11053. var distance;
  11054. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11055. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11056. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11057. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11058. }
  11059. else {
  11060. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11061. distance = meshesOrMinMaxVectorAndDistance.distance;
  11062. }
  11063. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11064. this.maxZ = distance * 2;
  11065. };
  11066. /**
  11067. * @override
  11068. * needs to be overridden, so sub has required properties to be copied
  11069. */
  11070. ArcRotateCamera.prototype.getSubCamera = function (name, isA) {
  11071. var alphaSpace = this._subCamHalfSpace * (isA ? -1 : 1);
  11072. return new BABYLON.ArcRotateCamera(name, this.alpha + alphaSpace, this.beta, this.radius, this.target, this.getScene());
  11073. };
  11074. /**
  11075. * @override
  11076. * needs to be overridden, adding copy of alpha, beta & radius
  11077. */
  11078. ArcRotateCamera.prototype._updateSubCameras = function () {
  11079. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  11080. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  11081. camA.alpha = this.alpha - this._subCamHalfSpace;
  11082. camB.alpha = this.alpha + this._subCamHalfSpace;
  11083. camA.beta = camB.beta = this.beta;
  11084. camA.radius = camB.radius = this.radius;
  11085. _super.prototype._updateSubCameras.call(this);
  11086. };
  11087. return ArcRotateCamera;
  11088. })(BABYLON.Camera);
  11089. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11090. })(BABYLON || (BABYLON = {}));
  11091. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  11092. var __extends = this.__extends || function (d, b) {
  11093. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11094. function __() { this.constructor = d; }
  11095. __.prototype = b.prototype;
  11096. d.prototype = new __();
  11097. };
  11098. var BABYLON;
  11099. (function (BABYLON) {
  11100. // We're mainly based on the logic defined into the FreeCamera code
  11101. var DeviceOrientationCamera = (function (_super) {
  11102. __extends(DeviceOrientationCamera, _super);
  11103. function DeviceOrientationCamera(name, position, scene) {
  11104. var _this = this;
  11105. _super.call(this, name, position, scene);
  11106. this._offsetX = null;
  11107. this._offsetY = null;
  11108. this._orientationGamma = 0;
  11109. this._orientationBeta = 0;
  11110. this._initialOrientationGamma = 0;
  11111. this._initialOrientationBeta = 0;
  11112. this.angularSensibility = 10000.0;
  11113. this.moveSensibility = 50.0;
  11114. window.addEventListener("resize", function () {
  11115. _this._initialOrientationGamma = null;
  11116. }, false);
  11117. }
  11118. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11119. var _this = this;
  11120. if (this._attachedCanvas) {
  11121. return;
  11122. }
  11123. this._attachedCanvas = canvas;
  11124. if (!this._orientationChanged) {
  11125. this._orientationChanged = function (evt) {
  11126. if (!_this._initialOrientationGamma) {
  11127. _this._initialOrientationGamma = evt.gamma;
  11128. _this._initialOrientationBeta = evt.beta;
  11129. }
  11130. _this._orientationGamma = evt.gamma;
  11131. _this._orientationBeta = evt.beta;
  11132. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11133. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11134. };
  11135. }
  11136. window.addEventListener("deviceorientation", this._orientationChanged);
  11137. };
  11138. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11139. if (this._attachedCanvas != canvas) {
  11140. return;
  11141. }
  11142. window.removeEventListener("deviceorientation", this._orientationChanged);
  11143. this._attachedCanvas = null;
  11144. this._orientationGamma = 0;
  11145. this._orientationBeta = 0;
  11146. this._initialOrientationGamma = 0;
  11147. this._initialOrientationBeta = 0;
  11148. };
  11149. DeviceOrientationCamera.prototype._checkInputs = function () {
  11150. if (!this._offsetX) {
  11151. return;
  11152. }
  11153. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11154. var speed = this._computeLocalCameraSpeed();
  11155. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11156. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11157. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11158. _super.prototype._checkInputs.call(this);
  11159. };
  11160. return DeviceOrientationCamera;
  11161. })(BABYLON.FreeCamera);
  11162. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11163. })(BABYLON || (BABYLON = {}));
  11164. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  11165. var BABYLON;
  11166. (function (BABYLON) {
  11167. var RenderingManager = (function () {
  11168. function RenderingManager(scene) {
  11169. this._renderingGroups = new Array();
  11170. this._scene = scene;
  11171. }
  11172. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11173. if (this._scene._activeParticleSystems.length === 0) {
  11174. return;
  11175. }
  11176. // Particles
  11177. var beforeParticlesDate = BABYLON.Tools.Now;
  11178. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11179. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11180. if (particleSystem.renderingGroupId !== index) {
  11181. continue;
  11182. }
  11183. this._clearDepthBuffer();
  11184. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11185. this._scene._activeParticles += particleSystem.render();
  11186. }
  11187. }
  11188. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11189. };
  11190. RenderingManager.prototype._renderSprites = function (index) {
  11191. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11192. return;
  11193. }
  11194. // Sprites
  11195. var beforeSpritessDate = BABYLON.Tools.Now;
  11196. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11197. var spriteManager = this._scene.spriteManagers[id];
  11198. if (spriteManager.renderingGroupId === index) {
  11199. this._clearDepthBuffer();
  11200. spriteManager.render();
  11201. }
  11202. }
  11203. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11204. };
  11205. RenderingManager.prototype._clearDepthBuffer = function () {
  11206. if (this._depthBufferAlreadyCleaned) {
  11207. return;
  11208. }
  11209. this._scene.getEngine().clear(0, false, true);
  11210. this._depthBufferAlreadyCleaned = true;
  11211. };
  11212. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11213. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11214. this._depthBufferAlreadyCleaned = false;
  11215. var renderingGroup = this._renderingGroups[index];
  11216. var needToStepBack = false;
  11217. if (renderingGroup) {
  11218. this._clearDepthBuffer();
  11219. if (!renderingGroup.render(customRenderFunction)) {
  11220. this._renderingGroups.splice(index, 1);
  11221. needToStepBack = true;
  11222. }
  11223. }
  11224. if (renderSprites) {
  11225. this._renderSprites(index);
  11226. }
  11227. if (renderParticles) {
  11228. this._renderParticles(index, activeMeshes);
  11229. }
  11230. if (needToStepBack) {
  11231. index--;
  11232. }
  11233. }
  11234. };
  11235. RenderingManager.prototype.reset = function () {
  11236. for (var index in this._renderingGroups) {
  11237. var renderingGroup = this._renderingGroups[index];
  11238. renderingGroup.prepare();
  11239. }
  11240. };
  11241. RenderingManager.prototype.dispatch = function (subMesh) {
  11242. var mesh = subMesh.getMesh();
  11243. var renderingGroupId = mesh.renderingGroupId || 0;
  11244. if (!this._renderingGroups[renderingGroupId]) {
  11245. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11246. }
  11247. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11248. };
  11249. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11250. return RenderingManager;
  11251. })();
  11252. BABYLON.RenderingManager = RenderingManager;
  11253. })(BABYLON || (BABYLON = {}));
  11254. //# sourceMappingURL=babylon.renderingManager.js.map
  11255. var BABYLON;
  11256. (function (BABYLON) {
  11257. var RenderingGroup = (function () {
  11258. function RenderingGroup(index, scene) {
  11259. this.index = index;
  11260. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11261. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11262. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11263. this._scene = scene;
  11264. }
  11265. RenderingGroup.prototype.render = function (customRenderFunction) {
  11266. if (customRenderFunction) {
  11267. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11268. return true;
  11269. }
  11270. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11271. return false;
  11272. }
  11273. var engine = this._scene.getEngine();
  11274. // Opaque
  11275. var subIndex;
  11276. var submesh;
  11277. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11278. submesh = this._opaqueSubMeshes.data[subIndex];
  11279. submesh.render();
  11280. }
  11281. // Alpha test
  11282. engine.setAlphaTesting(true);
  11283. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11284. submesh = this._alphaTestSubMeshes.data[subIndex];
  11285. submesh.render();
  11286. }
  11287. engine.setAlphaTesting(false);
  11288. // Transparent
  11289. if (this._transparentSubMeshes.length) {
  11290. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11291. submesh = this._transparentSubMeshes.data[subIndex];
  11292. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11293. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11294. }
  11295. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11296. sortedArray.sort(function (a, b) {
  11297. // Alpha index first
  11298. if (a._alphaIndex > b._alphaIndex) {
  11299. return 1;
  11300. }
  11301. if (a._alphaIndex < b._alphaIndex) {
  11302. return -1;
  11303. }
  11304. // Then distance to camera
  11305. if (a._distanceToCamera < b._distanceToCamera) {
  11306. return 1;
  11307. }
  11308. if (a._distanceToCamera > b._distanceToCamera) {
  11309. return -1;
  11310. }
  11311. return 0;
  11312. });
  11313. // Rendering
  11314. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11315. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11316. submesh = sortedArray[subIndex];
  11317. submesh.render();
  11318. }
  11319. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11320. }
  11321. return true;
  11322. };
  11323. RenderingGroup.prototype.prepare = function () {
  11324. this._opaqueSubMeshes.reset();
  11325. this._transparentSubMeshes.reset();
  11326. this._alphaTestSubMeshes.reset();
  11327. };
  11328. RenderingGroup.prototype.dispatch = function (subMesh) {
  11329. var material = subMesh.getMaterial();
  11330. var mesh = subMesh.getMesh();
  11331. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11332. this._transparentSubMeshes.push(subMesh);
  11333. }
  11334. else if (material.needAlphaTesting()) {
  11335. this._alphaTestSubMeshes.push(subMesh);
  11336. }
  11337. else {
  11338. this._opaqueSubMeshes.push(subMesh); // Opaque
  11339. }
  11340. };
  11341. return RenderingGroup;
  11342. })();
  11343. BABYLON.RenderingGroup = RenderingGroup;
  11344. })(BABYLON || (BABYLON = {}));
  11345. //# sourceMappingURL=babylon.renderingGroup.js.map
  11346. var BABYLON;
  11347. (function (BABYLON) {
  11348. /**
  11349. * Represents a scene to be rendered by the engine.
  11350. * @see http://doc.babylonjs.com/page.php?p=21911
  11351. */
  11352. var Scene = (function () {
  11353. /**
  11354. * @constructor
  11355. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11356. */
  11357. function Scene(engine) {
  11358. // Members
  11359. this.autoClear = true;
  11360. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11361. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11362. this.forceWireframe = false;
  11363. this.forcePointsCloud = false;
  11364. this.forceShowBoundingBoxes = false;
  11365. this.animationsEnabled = true;
  11366. 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
  11367. // Fog
  11368. /**
  11369. * is fog enabled on this scene.
  11370. * @type {boolean}
  11371. */
  11372. this.fogEnabled = true;
  11373. this.fogMode = Scene.FOGMODE_NONE;
  11374. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11375. this.fogDensity = 0.1;
  11376. this.fogStart = 0;
  11377. this.fogEnd = 1000.0;
  11378. // Lights
  11379. /**
  11380. * is shadow enabled on this scene.
  11381. * @type {boolean}
  11382. */
  11383. this.shadowsEnabled = true;
  11384. /**
  11385. * is light enabled on this scene.
  11386. * @type {boolean}
  11387. */
  11388. this.lightsEnabled = true;
  11389. /**
  11390. * All of the lights added to this scene.
  11391. * @see BABYLON.Light
  11392. * @type {BABYLON.Light[]}
  11393. */
  11394. this.lights = new Array();
  11395. // Cameras
  11396. /**
  11397. * All of the cameras added to this scene.
  11398. * @see BABYLON.Camera
  11399. * @type {BABYLON.Camera[]}
  11400. */
  11401. this.cameras = new Array();
  11402. this.activeCameras = new Array();
  11403. // Meshes
  11404. /**
  11405. * All of the (abstract) meshes added to this scene.
  11406. * @see BABYLON.AbstractMesh
  11407. * @type {BABYLON.AbstractMesh[]}
  11408. */
  11409. this.meshes = new Array();
  11410. // Geometries
  11411. this._geometries = new Array();
  11412. this.materials = new Array();
  11413. this.multiMaterials = new Array();
  11414. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  11415. // Textures
  11416. this.texturesEnabled = true;
  11417. this.textures = new Array();
  11418. // Particles
  11419. this.particlesEnabled = true;
  11420. this.particleSystems = new Array();
  11421. // Sprites
  11422. this.spritesEnabled = true;
  11423. this.spriteManagers = new Array();
  11424. // Layers
  11425. this.layers = new Array();
  11426. // Skeletons
  11427. this.skeletonsEnabled = true;
  11428. this.skeletons = new Array();
  11429. // Lens flares
  11430. this.lensFlaresEnabled = true;
  11431. this.lensFlareSystems = new Array();
  11432. // Collisions
  11433. this.collisionsEnabled = true;
  11434. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  11435. // Postprocesses
  11436. this.postProcessesEnabled = true;
  11437. // Customs render targets
  11438. this.renderTargetsEnabled = true;
  11439. this.dumpNextRenderTargets = false;
  11440. this.customRenderTargets = new Array();
  11441. // Imported meshes
  11442. this.importedMeshesFiles = new Array();
  11443. this._actionManagers = new Array();
  11444. this._meshesForIntersections = new BABYLON.SmartArray(256);
  11445. // Procedural textures
  11446. this.proceduralTexturesEnabled = true;
  11447. this._proceduralTextures = new Array();
  11448. this.soundTracks = new Array();
  11449. this._audioEnabled = true;
  11450. this._headphone = false;
  11451. this._totalVertices = 0;
  11452. this._activeIndices = 0;
  11453. this._activeParticles = 0;
  11454. this._lastFrameDuration = 0;
  11455. this._evaluateActiveMeshesDuration = 0;
  11456. this._renderTargetsDuration = 0;
  11457. this._particlesDuration = 0;
  11458. this._renderDuration = 0;
  11459. this._spritesDuration = 0;
  11460. this._animationRatio = 0;
  11461. this._renderId = 0;
  11462. this._executeWhenReadyTimeoutId = -1;
  11463. this._toBeDisposed = new BABYLON.SmartArray(256);
  11464. this._onReadyCallbacks = new Array();
  11465. this._pendingData = []; //ANY
  11466. this._onBeforeRenderCallbacks = new Array();
  11467. this._onAfterRenderCallbacks = new Array();
  11468. this._activeMeshes = new BABYLON.SmartArray(256);
  11469. this._processedMaterials = new BABYLON.SmartArray(256);
  11470. this._renderTargets = new BABYLON.SmartArray(256);
  11471. this._activeParticleSystems = new BABYLON.SmartArray(256);
  11472. this._activeSkeletons = new BABYLON.SmartArray(32);
  11473. this._activeBones = 0;
  11474. this._activeAnimatables = new Array();
  11475. this._transformMatrix = BABYLON.Matrix.Zero();
  11476. this._uniqueIdCounter = 0;
  11477. this._engine = engine;
  11478. engine.scenes.push(this);
  11479. this._renderingManager = new BABYLON.RenderingManager(this);
  11480. this.postProcessManager = new BABYLON.PostProcessManager(this);
  11481. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  11482. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  11483. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  11484. this.attachControl();
  11485. this._debugLayer = new BABYLON.DebugLayer(this);
  11486. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  11487. //simplification queue
  11488. this.simplificationQueue = new BABYLON.SimplificationQueue();
  11489. //collision coordinator initialization. For now legacy per default.
  11490. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  11491. }
  11492. Object.defineProperty(Scene, "FOGMODE_NONE", {
  11493. get: function () {
  11494. return Scene._FOGMODE_NONE;
  11495. },
  11496. enumerable: true,
  11497. configurable: true
  11498. });
  11499. Object.defineProperty(Scene, "FOGMODE_EXP", {
  11500. get: function () {
  11501. return Scene._FOGMODE_EXP;
  11502. },
  11503. enumerable: true,
  11504. configurable: true
  11505. });
  11506. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  11507. get: function () {
  11508. return Scene._FOGMODE_EXP2;
  11509. },
  11510. enumerable: true,
  11511. configurable: true
  11512. });
  11513. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  11514. get: function () {
  11515. return Scene._FOGMODE_LINEAR;
  11516. },
  11517. enumerable: true,
  11518. configurable: true
  11519. });
  11520. Object.defineProperty(Scene.prototype, "debugLayer", {
  11521. // Properties
  11522. get: function () {
  11523. return this._debugLayer;
  11524. },
  11525. enumerable: true,
  11526. configurable: true
  11527. });
  11528. Object.defineProperty(Scene.prototype, "workerCollisions", {
  11529. get: function () {
  11530. return this._workerCollisions;
  11531. },
  11532. set: function (enabled) {
  11533. enabled = (enabled && !!Worker);
  11534. this._workerCollisions = enabled;
  11535. if (this.collisionCoordinator) {
  11536. this.collisionCoordinator.destroy();
  11537. }
  11538. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  11539. this.collisionCoordinator.init(this);
  11540. },
  11541. enumerable: true,
  11542. configurable: true
  11543. });
  11544. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  11545. /**
  11546. * The mesh that is currently under the pointer.
  11547. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  11548. */
  11549. get: function () {
  11550. return this._meshUnderPointer;
  11551. },
  11552. enumerable: true,
  11553. configurable: true
  11554. });
  11555. Object.defineProperty(Scene.prototype, "pointerX", {
  11556. /**
  11557. * Current on-screen X position of the pointer
  11558. * @return {number} X position of the pointer
  11559. */
  11560. get: function () {
  11561. return this._pointerX;
  11562. },
  11563. enumerable: true,
  11564. configurable: true
  11565. });
  11566. Object.defineProperty(Scene.prototype, "pointerY", {
  11567. /**
  11568. * Current on-screen Y position of the pointer
  11569. * @return {number} Y position of the pointer
  11570. */
  11571. get: function () {
  11572. return this._pointerY;
  11573. },
  11574. enumerable: true,
  11575. configurable: true
  11576. });
  11577. Scene.prototype.getCachedMaterial = function () {
  11578. return this._cachedMaterial;
  11579. };
  11580. Scene.prototype.getBoundingBoxRenderer = function () {
  11581. return this._boundingBoxRenderer;
  11582. };
  11583. Scene.prototype.getOutlineRenderer = function () {
  11584. return this._outlineRenderer;
  11585. };
  11586. Scene.prototype.getEngine = function () {
  11587. return this._engine;
  11588. };
  11589. Scene.prototype.getTotalVertices = function () {
  11590. return this._totalVertices;
  11591. };
  11592. Scene.prototype.getActiveIndices = function () {
  11593. return this._activeIndices;
  11594. };
  11595. Scene.prototype.getActiveParticles = function () {
  11596. return this._activeParticles;
  11597. };
  11598. Scene.prototype.getActiveBones = function () {
  11599. return this._activeBones;
  11600. };
  11601. // Stats
  11602. Scene.prototype.getLastFrameDuration = function () {
  11603. return this._lastFrameDuration;
  11604. };
  11605. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  11606. return this._evaluateActiveMeshesDuration;
  11607. };
  11608. Scene.prototype.getActiveMeshes = function () {
  11609. return this._activeMeshes;
  11610. };
  11611. Scene.prototype.getRenderTargetsDuration = function () {
  11612. return this._renderTargetsDuration;
  11613. };
  11614. Scene.prototype.getRenderDuration = function () {
  11615. return this._renderDuration;
  11616. };
  11617. Scene.prototype.getParticlesDuration = function () {
  11618. return this._particlesDuration;
  11619. };
  11620. Scene.prototype.getSpritesDuration = function () {
  11621. return this._spritesDuration;
  11622. };
  11623. Scene.prototype.getAnimationRatio = function () {
  11624. return this._animationRatio;
  11625. };
  11626. Scene.prototype.getRenderId = function () {
  11627. return this._renderId;
  11628. };
  11629. Scene.prototype.incrementRenderId = function () {
  11630. this._renderId++;
  11631. };
  11632. Scene.prototype._updatePointerPosition = function (evt) {
  11633. var canvasRect = this._engine.getRenderingCanvasClientRect();
  11634. this._pointerX = evt.clientX - canvasRect.left;
  11635. this._pointerY = evt.clientY - canvasRect.top;
  11636. if (this.cameraToUseForPointers) {
  11637. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  11638. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  11639. }
  11640. };
  11641. // Pointers handling
  11642. Scene.prototype.attachControl = function () {
  11643. var _this = this;
  11644. this._onPointerMove = function (evt) {
  11645. var canvas = _this._engine.getRenderingCanvas();
  11646. _this._updatePointerPosition(evt);
  11647. 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);
  11648. if (pickResult.hit) {
  11649. _this._meshUnderPointer = pickResult.pickedMesh;
  11650. _this.setPointerOverMesh(pickResult.pickedMesh);
  11651. canvas.style.cursor = "pointer";
  11652. }
  11653. else {
  11654. _this.setPointerOverMesh(null);
  11655. canvas.style.cursor = "";
  11656. _this._meshUnderPointer = null;
  11657. }
  11658. };
  11659. this._onPointerDown = function (evt) {
  11660. var predicate = null;
  11661. if (!_this.onPointerDown) {
  11662. predicate = function (mesh) {
  11663. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  11664. };
  11665. }
  11666. _this._updatePointerPosition(evt);
  11667. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11668. if (pickResult.hit) {
  11669. if (pickResult.pickedMesh.actionManager) {
  11670. switch (evt.button) {
  11671. case 0:
  11672. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11673. break;
  11674. case 1:
  11675. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11676. break;
  11677. case 2:
  11678. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11679. break;
  11680. }
  11681. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11682. }
  11683. }
  11684. if (_this.onPointerDown) {
  11685. _this.onPointerDown(evt, pickResult);
  11686. }
  11687. };
  11688. this._onPointerUp = function (evt) {
  11689. var predicate = null;
  11690. if (!_this.onPointerUp) {
  11691. predicate = function (mesh) {
  11692. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  11693. };
  11694. }
  11695. _this._updatePointerPosition(evt);
  11696. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  11697. if (pickResult.hit) {
  11698. if (pickResult.pickedMesh.actionManager) {
  11699. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  11700. }
  11701. }
  11702. if (_this.onPointerUp) {
  11703. _this.onPointerUp(evt, pickResult);
  11704. }
  11705. };
  11706. this._onKeyDown = function (evt) {
  11707. if (_this.actionManager) {
  11708. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11709. }
  11710. };
  11711. this._onKeyUp = function (evt) {
  11712. if (_this.actionManager) {
  11713. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  11714. }
  11715. };
  11716. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11717. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11718. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11719. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11720. BABYLON.Tools.RegisterTopRootEvents([
  11721. { name: "keydown", handler: this._onKeyDown },
  11722. { name: "keyup", handler: this._onKeyUp }
  11723. ]);
  11724. };
  11725. Scene.prototype.detachControl = function () {
  11726. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  11727. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  11728. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  11729. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  11730. BABYLON.Tools.UnregisterTopRootEvents([
  11731. { name: "keydown", handler: this._onKeyDown },
  11732. { name: "keyup", handler: this._onKeyUp }
  11733. ]);
  11734. };
  11735. // Ready
  11736. Scene.prototype.isReady = function () {
  11737. if (this._pendingData.length > 0) {
  11738. return false;
  11739. }
  11740. for (var index = 0; index < this._geometries.length; index++) {
  11741. var geometry = this._geometries[index];
  11742. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11743. return false;
  11744. }
  11745. }
  11746. for (index = 0; index < this.meshes.length; index++) {
  11747. var mesh = this.meshes[index];
  11748. if (!mesh.isReady()) {
  11749. return false;
  11750. }
  11751. var mat = mesh.material;
  11752. if (mat) {
  11753. if (!mat.isReady(mesh)) {
  11754. return false;
  11755. }
  11756. }
  11757. }
  11758. return true;
  11759. };
  11760. Scene.prototype.resetCachedMaterial = function () {
  11761. this._cachedMaterial = null;
  11762. };
  11763. Scene.prototype.registerBeforeRender = function (func) {
  11764. this._onBeforeRenderCallbacks.push(func);
  11765. };
  11766. Scene.prototype.unregisterBeforeRender = function (func) {
  11767. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11768. if (index > -1) {
  11769. this._onBeforeRenderCallbacks.splice(index, 1);
  11770. }
  11771. };
  11772. Scene.prototype.registerAfterRender = function (func) {
  11773. this._onAfterRenderCallbacks.push(func);
  11774. };
  11775. Scene.prototype.unregisterAfterRender = function (func) {
  11776. var index = this._onAfterRenderCallbacks.indexOf(func);
  11777. if (index > -1) {
  11778. this._onAfterRenderCallbacks.splice(index, 1);
  11779. }
  11780. };
  11781. Scene.prototype._addPendingData = function (data) {
  11782. this._pendingData.push(data);
  11783. };
  11784. Scene.prototype._removePendingData = function (data) {
  11785. var index = this._pendingData.indexOf(data);
  11786. if (index !== -1) {
  11787. this._pendingData.splice(index, 1);
  11788. }
  11789. };
  11790. Scene.prototype.getWaitingItemsCount = function () {
  11791. return this._pendingData.length;
  11792. };
  11793. /**
  11794. * Registers a function to be executed when the scene is ready.
  11795. * @param {Function} func - the function to be executed.
  11796. */
  11797. Scene.prototype.executeWhenReady = function (func) {
  11798. var _this = this;
  11799. this._onReadyCallbacks.push(func);
  11800. if (this._executeWhenReadyTimeoutId !== -1) {
  11801. return;
  11802. }
  11803. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11804. _this._checkIsReady();
  11805. }, 150);
  11806. };
  11807. Scene.prototype._checkIsReady = function () {
  11808. var _this = this;
  11809. if (this.isReady()) {
  11810. this._onReadyCallbacks.forEach(function (func) {
  11811. func();
  11812. });
  11813. this._onReadyCallbacks = [];
  11814. this._executeWhenReadyTimeoutId = -1;
  11815. return;
  11816. }
  11817. this._executeWhenReadyTimeoutId = setTimeout(function () {
  11818. _this._checkIsReady();
  11819. }, 150);
  11820. };
  11821. // Animations
  11822. /**
  11823. * Will start the animation sequence of a given target
  11824. * @param target - the target
  11825. * @param {number} from - from which frame should animation start
  11826. * @param {number} to - till which frame should animation run.
  11827. * @param {boolean} [loop] - should the animation loop
  11828. * @param {number} [speedRatio] - the speed in which to run the animation
  11829. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  11830. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  11831. * @return {BABYLON.Animatable} the animatable object created for this animation
  11832. * @see BABYLON.Animatable
  11833. * @see http://doc.babylonjs.com/page.php?p=22081
  11834. */
  11835. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  11836. if (speedRatio === undefined) {
  11837. speedRatio = 1.0;
  11838. }
  11839. this.stopAnimation(target);
  11840. if (!animatable) {
  11841. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  11842. }
  11843. // Local animations
  11844. if (target.animations) {
  11845. animatable.appendAnimations(target, target.animations);
  11846. }
  11847. // Children animations
  11848. if (target.getAnimatables) {
  11849. var animatables = target.getAnimatables();
  11850. for (var index = 0; index < animatables.length; index++) {
  11851. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  11852. }
  11853. }
  11854. return animatable;
  11855. };
  11856. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  11857. if (speedRatio === undefined) {
  11858. speedRatio = 1.0;
  11859. }
  11860. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  11861. return animatable;
  11862. };
  11863. Scene.prototype.getAnimatableByTarget = function (target) {
  11864. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11865. if (this._activeAnimatables[index].target === target) {
  11866. return this._activeAnimatables[index];
  11867. }
  11868. }
  11869. return null;
  11870. };
  11871. /**
  11872. * Will stop the animation of the given target
  11873. * @param target - the target
  11874. * @see beginAnimation
  11875. */
  11876. Scene.prototype.stopAnimation = function (target) {
  11877. var animatable = this.getAnimatableByTarget(target);
  11878. if (animatable) {
  11879. animatable.stop();
  11880. }
  11881. };
  11882. Scene.prototype._animate = function () {
  11883. if (!this.animationsEnabled) {
  11884. return;
  11885. }
  11886. if (!this._animationStartDate) {
  11887. this._animationStartDate = BABYLON.Tools.Now;
  11888. }
  11889. // Getting time
  11890. var now = BABYLON.Tools.Now;
  11891. var delay = now - this._animationStartDate;
  11892. for (var index = 0; index < this._activeAnimatables.length; index++) {
  11893. this._activeAnimatables[index]._animate(delay);
  11894. }
  11895. };
  11896. // Matrix
  11897. Scene.prototype.getViewMatrix = function () {
  11898. return this._viewMatrix;
  11899. };
  11900. Scene.prototype.getProjectionMatrix = function () {
  11901. return this._projectionMatrix;
  11902. };
  11903. Scene.prototype.getTransformMatrix = function () {
  11904. return this._transformMatrix;
  11905. };
  11906. Scene.prototype.setTransformMatrix = function (view, projection) {
  11907. this._viewMatrix = view;
  11908. this._projectionMatrix = projection;
  11909. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11910. };
  11911. // Methods
  11912. Scene.prototype.addMesh = function (newMesh) {
  11913. newMesh.uniqueId = this._uniqueIdCounter++;
  11914. var position = this.meshes.push(newMesh);
  11915. //notify the collision coordinator
  11916. this.collisionCoordinator.onMeshAdded(newMesh);
  11917. if (this.onNewMeshAdded) {
  11918. this.onNewMeshAdded(newMesh, position, this);
  11919. }
  11920. };
  11921. Scene.prototype.removeMesh = function (toRemove) {
  11922. var index = this.meshes.indexOf(toRemove);
  11923. if (index !== -1) {
  11924. // Remove from the scene if mesh found
  11925. this.meshes.splice(index, 1);
  11926. }
  11927. //notify the collision coordinator
  11928. this.collisionCoordinator.onMeshRemoved(toRemove);
  11929. if (this.onMeshRemoved) {
  11930. this.onMeshRemoved(toRemove);
  11931. }
  11932. return index;
  11933. };
  11934. Scene.prototype.removeLight = function (toRemove) {
  11935. var index = this.lights.indexOf(toRemove);
  11936. if (index !== -1) {
  11937. // Remove from the scene if mesh found
  11938. this.lights.splice(index, 1);
  11939. }
  11940. if (this.onLightRemoved) {
  11941. this.onLightRemoved(toRemove);
  11942. }
  11943. return index;
  11944. };
  11945. Scene.prototype.removeCamera = function (toRemove) {
  11946. var index = this.cameras.indexOf(toRemove);
  11947. if (index !== -1) {
  11948. // Remove from the scene if mesh found
  11949. this.cameras.splice(index, 1);
  11950. }
  11951. // Remove from activeCameras
  11952. var index2 = this.activeCameras.indexOf(toRemove);
  11953. if (index2 !== -1) {
  11954. // Remove from the scene if mesh found
  11955. this.activeCameras.splice(index2, 1);
  11956. }
  11957. // Reset the activeCamera
  11958. if (this.activeCamera === toRemove) {
  11959. if (this.cameras.length > 0) {
  11960. this.activeCamera = this.cameras[0];
  11961. }
  11962. else {
  11963. this.activeCamera = null;
  11964. }
  11965. }
  11966. if (this.onCameraRemoved) {
  11967. this.onCameraRemoved(toRemove);
  11968. }
  11969. return index;
  11970. };
  11971. Scene.prototype.addLight = function (newLight) {
  11972. newLight.uniqueId = this._uniqueIdCounter++;
  11973. var position = this.lights.push(newLight);
  11974. if (this.onNewLightAdded) {
  11975. this.onNewLightAdded(newLight, position, this);
  11976. }
  11977. };
  11978. Scene.prototype.addCamera = function (newCamera) {
  11979. newCamera.uniqueId = this._uniqueIdCounter++;
  11980. var position = this.cameras.push(newCamera);
  11981. if (this.onNewCameraAdded) {
  11982. this.onNewCameraAdded(newCamera, position, this);
  11983. }
  11984. };
  11985. /**
  11986. * sets the active camera of the scene using its ID
  11987. * @param {string} id - the camera's ID
  11988. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  11989. * @see activeCamera
  11990. */
  11991. Scene.prototype.setActiveCameraByID = function (id) {
  11992. var camera = this.getCameraByID(id);
  11993. if (camera) {
  11994. this.activeCamera = camera;
  11995. return camera;
  11996. }
  11997. return null;
  11998. };
  11999. /**
  12000. * sets the active camera of the scene using its name
  12001. * @param {string} name - the camera's name
  12002. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12003. * @see activeCamera
  12004. */
  12005. Scene.prototype.setActiveCameraByName = function (name) {
  12006. var camera = this.getCameraByName(name);
  12007. if (camera) {
  12008. this.activeCamera = camera;
  12009. return camera;
  12010. }
  12011. return null;
  12012. };
  12013. /**
  12014. * get a material using its id
  12015. * @param {string} the material's ID
  12016. * @return {BABYLON.Material|null} the material or null if none found.
  12017. */
  12018. Scene.prototype.getMaterialByID = function (id) {
  12019. for (var index = 0; index < this.materials.length; index++) {
  12020. if (this.materials[index].id === id) {
  12021. return this.materials[index];
  12022. }
  12023. }
  12024. return null;
  12025. };
  12026. /**
  12027. * get a material using its name
  12028. * @param {string} the material's name
  12029. * @return {BABYLON.Material|null} the material or null if none found.
  12030. */
  12031. Scene.prototype.getMaterialByName = function (name) {
  12032. for (var index = 0; index < this.materials.length; index++) {
  12033. if (this.materials[index].name === name) {
  12034. return this.materials[index];
  12035. }
  12036. }
  12037. return null;
  12038. };
  12039. Scene.prototype.getCameraByID = function (id) {
  12040. for (var index = 0; index < this.cameras.length; index++) {
  12041. if (this.cameras[index].id === id) {
  12042. return this.cameras[index];
  12043. }
  12044. }
  12045. return null;
  12046. };
  12047. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12048. for (var index = 0; index < this.cameras.length; index++) {
  12049. if (this.cameras[index].uniqueId === uniqueId) {
  12050. return this.cameras[index];
  12051. }
  12052. }
  12053. return null;
  12054. };
  12055. /**
  12056. * get a camera using its name
  12057. * @param {string} the camera's name
  12058. * @return {BABYLON.Camera|null} the camera or null if none found.
  12059. */
  12060. Scene.prototype.getCameraByName = function (name) {
  12061. for (var index = 0; index < this.cameras.length; index++) {
  12062. if (this.cameras[index].name === name) {
  12063. return this.cameras[index];
  12064. }
  12065. }
  12066. return null;
  12067. };
  12068. /**
  12069. * get a light node using its name
  12070. * @param {string} the light's name
  12071. * @return {BABYLON.Light|null} the light or null if none found.
  12072. */
  12073. Scene.prototype.getLightByName = function (name) {
  12074. for (var index = 0; index < this.lights.length; index++) {
  12075. if (this.lights[index].name === name) {
  12076. return this.lights[index];
  12077. }
  12078. }
  12079. return null;
  12080. };
  12081. /**
  12082. * get a light node using its ID
  12083. * @param {string} the light's id
  12084. * @return {BABYLON.Light|null} the light or null if none found.
  12085. */
  12086. Scene.prototype.getLightByID = function (id) {
  12087. for (var index = 0; index < this.lights.length; index++) {
  12088. if (this.lights[index].id === id) {
  12089. return this.lights[index];
  12090. }
  12091. }
  12092. return null;
  12093. };
  12094. /**
  12095. * get a light node using its scene-generated unique ID
  12096. * @param {number} the light's unique id
  12097. * @return {BABYLON.Light|null} the light or null if none found.
  12098. */
  12099. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12100. for (var index = 0; index < this.lights.length; index++) {
  12101. if (this.lights[index].uniqueId === uniqueId) {
  12102. return this.lights[index];
  12103. }
  12104. }
  12105. return null;
  12106. };
  12107. /**
  12108. * get a geometry using its ID
  12109. * @param {string} the geometry's id
  12110. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12111. */
  12112. Scene.prototype.getGeometryByID = function (id) {
  12113. for (var index = 0; index < this._geometries.length; index++) {
  12114. if (this._geometries[index].id === id) {
  12115. return this._geometries[index];
  12116. }
  12117. }
  12118. return null;
  12119. };
  12120. /**
  12121. * add a new geometry to this scene.
  12122. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12123. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12124. * @return {boolean} was the geometry added or not
  12125. */
  12126. Scene.prototype.pushGeometry = function (geometry, force) {
  12127. if (!force && this.getGeometryByID(geometry.id)) {
  12128. return false;
  12129. }
  12130. this._geometries.push(geometry);
  12131. //notify the collision coordinator
  12132. this.collisionCoordinator.onGeometryAdded(geometry);
  12133. if (this.onGeometryAdded) {
  12134. this.onGeometryAdded(geometry);
  12135. }
  12136. return true;
  12137. };
  12138. /**
  12139. * Removes an existing geometry
  12140. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12141. * @return {boolean} was the geometry removed or not
  12142. */
  12143. Scene.prototype.removeGeometry = function (geometry) {
  12144. var index = this._geometries.indexOf(geometry);
  12145. if (index > -1) {
  12146. this._geometries.splice(index, 1);
  12147. //notify the collision coordinator
  12148. this.collisionCoordinator.onGeometryDeleted(geometry);
  12149. if (this.onGeometryRemoved) {
  12150. this.onGeometryRemoved(geometry);
  12151. }
  12152. return true;
  12153. }
  12154. return false;
  12155. };
  12156. Scene.prototype.getGeometries = function () {
  12157. return this._geometries;
  12158. };
  12159. /**
  12160. * Get the first added mesh found of a given ID
  12161. * @param {string} id - the id to search for
  12162. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12163. */
  12164. Scene.prototype.getMeshByID = function (id) {
  12165. for (var index = 0; index < this.meshes.length; index++) {
  12166. if (this.meshes[index].id === id) {
  12167. return this.meshes[index];
  12168. }
  12169. }
  12170. return null;
  12171. };
  12172. /**
  12173. * Get a mesh with its auto-generated unique id
  12174. * @param {number} uniqueId - the unique id to search for
  12175. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12176. */
  12177. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12178. for (var index = 0; index < this.meshes.length; index++) {
  12179. if (this.meshes[index].uniqueId === uniqueId) {
  12180. return this.meshes[index];
  12181. }
  12182. }
  12183. return null;
  12184. };
  12185. /**
  12186. * Get a the last added mesh found of a given ID
  12187. * @param {string} id - the id to search for
  12188. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12189. */
  12190. Scene.prototype.getLastMeshByID = function (id) {
  12191. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12192. if (this.meshes[index].id === id) {
  12193. return this.meshes[index];
  12194. }
  12195. }
  12196. return null;
  12197. };
  12198. /**
  12199. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12200. * @param {string} id - the id to search for
  12201. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12202. */
  12203. Scene.prototype.getLastEntryByID = function (id) {
  12204. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12205. if (this.meshes[index].id === id) {
  12206. return this.meshes[index];
  12207. }
  12208. }
  12209. for (index = this.cameras.length - 1; index >= 0; index--) {
  12210. if (this.cameras[index].id === id) {
  12211. return this.cameras[index];
  12212. }
  12213. }
  12214. for (index = this.lights.length - 1; index >= 0; index--) {
  12215. if (this.lights[index].id === id) {
  12216. return this.lights[index];
  12217. }
  12218. }
  12219. return null;
  12220. };
  12221. Scene.prototype.getNodeByName = function (name) {
  12222. var mesh = this.getMeshByName(name);
  12223. if (mesh) {
  12224. return mesh;
  12225. }
  12226. var light = this.getLightByName(name);
  12227. if (light) {
  12228. return light;
  12229. }
  12230. return this.getCameraByName(name);
  12231. };
  12232. Scene.prototype.getMeshByName = function (name) {
  12233. for (var index = 0; index < this.meshes.length; index++) {
  12234. if (this.meshes[index].name === name) {
  12235. return this.meshes[index];
  12236. }
  12237. }
  12238. return null;
  12239. };
  12240. Scene.prototype.getSoundByName = function (name) {
  12241. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12242. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12243. return this.mainSoundTrack.soundCollection[index];
  12244. }
  12245. }
  12246. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12247. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12248. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12249. return this.soundTracks[sdIndex].soundCollection[index];
  12250. }
  12251. }
  12252. }
  12253. return null;
  12254. };
  12255. Scene.prototype.getLastSkeletonByID = function (id) {
  12256. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12257. if (this.skeletons[index].id === id) {
  12258. return this.skeletons[index];
  12259. }
  12260. }
  12261. return null;
  12262. };
  12263. Scene.prototype.getSkeletonById = function (id) {
  12264. for (var index = 0; index < this.skeletons.length; index++) {
  12265. if (this.skeletons[index].id === id) {
  12266. return this.skeletons[index];
  12267. }
  12268. }
  12269. return null;
  12270. };
  12271. Scene.prototype.getSkeletonByName = function (name) {
  12272. for (var index = 0; index < this.skeletons.length; index++) {
  12273. if (this.skeletons[index].name === name) {
  12274. return this.skeletons[index];
  12275. }
  12276. }
  12277. return null;
  12278. };
  12279. Scene.prototype.isActiveMesh = function (mesh) {
  12280. return (this._activeMeshes.indexOf(mesh) !== -1);
  12281. };
  12282. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12283. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12284. var material = subMesh.getMaterial();
  12285. if (mesh.showSubMeshesBoundingBox) {
  12286. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12287. }
  12288. if (material) {
  12289. // Render targets
  12290. if (material.getRenderTargetTextures) {
  12291. if (this._processedMaterials.indexOf(material) === -1) {
  12292. this._processedMaterials.push(material);
  12293. this._renderTargets.concat(material.getRenderTargetTextures());
  12294. }
  12295. }
  12296. // Dispatch
  12297. this._activeIndices += subMesh.indexCount;
  12298. this._renderingManager.dispatch(subMesh);
  12299. }
  12300. }
  12301. };
  12302. Scene.prototype._evaluateActiveMeshes = function () {
  12303. this.activeCamera._activeMeshes.reset();
  12304. this._activeMeshes.reset();
  12305. this._renderingManager.reset();
  12306. this._processedMaterials.reset();
  12307. this._activeParticleSystems.reset();
  12308. this._activeSkeletons.reset();
  12309. this._boundingBoxRenderer.reset();
  12310. if (!this._frustumPlanes) {
  12311. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12312. }
  12313. else {
  12314. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12315. }
  12316. // Meshes
  12317. var meshes;
  12318. var len;
  12319. if (this._selectionOctree) {
  12320. var selection = this._selectionOctree.select(this._frustumPlanes);
  12321. meshes = selection.data;
  12322. len = selection.length;
  12323. }
  12324. else {
  12325. len = this.meshes.length;
  12326. meshes = this.meshes;
  12327. }
  12328. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12329. var mesh = meshes[meshIndex];
  12330. if (mesh.isBlocked) {
  12331. continue;
  12332. }
  12333. this._totalVertices += mesh.getTotalVertices();
  12334. if (!mesh.isReady() || !mesh.isEnabled()) {
  12335. continue;
  12336. }
  12337. mesh.computeWorldMatrix();
  12338. // Intersections
  12339. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12340. this._meshesForIntersections.pushNoDuplicate(mesh);
  12341. }
  12342. // Switch to current LOD
  12343. var meshLOD = mesh.getLOD(this.activeCamera);
  12344. if (!meshLOD) {
  12345. continue;
  12346. }
  12347. mesh._preActivate();
  12348. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  12349. this._activeMeshes.push(mesh);
  12350. this.activeCamera._activeMeshes.push(mesh);
  12351. mesh._activate(this._renderId);
  12352. this._activeMesh(meshLOD);
  12353. }
  12354. }
  12355. // Particle systems
  12356. var beforeParticlesDate = BABYLON.Tools.Now;
  12357. if (this.particlesEnabled) {
  12358. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12359. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12360. var particleSystem = this.particleSystems[particleIndex];
  12361. if (!particleSystem.isStarted()) {
  12362. continue;
  12363. }
  12364. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12365. this._activeParticleSystems.push(particleSystem);
  12366. particleSystem.animate();
  12367. }
  12368. }
  12369. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  12370. }
  12371. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12372. };
  12373. Scene.prototype._activeMesh = function (mesh) {
  12374. if (mesh.skeleton && this.skeletonsEnabled) {
  12375. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  12376. }
  12377. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  12378. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  12379. }
  12380. if (mesh && mesh.subMeshes) {
  12381. // Submeshes Octrees
  12382. var len;
  12383. var subMeshes;
  12384. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  12385. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  12386. len = intersections.length;
  12387. subMeshes = intersections.data;
  12388. }
  12389. else {
  12390. subMeshes = mesh.subMeshes;
  12391. len = subMeshes.length;
  12392. }
  12393. for (var subIndex = 0; subIndex < len; subIndex++) {
  12394. var subMesh = subMeshes[subIndex];
  12395. this._evaluateSubMesh(subMesh, mesh);
  12396. }
  12397. }
  12398. };
  12399. Scene.prototype.updateTransformMatrix = function (force) {
  12400. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  12401. };
  12402. Scene.prototype._renderForCamera = function (camera) {
  12403. var engine = this._engine;
  12404. this.activeCamera = camera;
  12405. if (!this.activeCamera)
  12406. throw new Error("Active camera not set");
  12407. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12408. // Viewport
  12409. engine.setViewport(this.activeCamera.viewport);
  12410. // Camera
  12411. this._renderId++;
  12412. this.updateTransformMatrix();
  12413. if (this.beforeCameraRender) {
  12414. this.beforeCameraRender(this.activeCamera);
  12415. }
  12416. // Meshes
  12417. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  12418. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  12419. this._evaluateActiveMeshes();
  12420. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  12421. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  12422. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  12423. var skeleton = this._activeSkeletons.data[skeletonIndex];
  12424. skeleton.prepare();
  12425. }
  12426. // Render targets
  12427. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12428. if (this.renderTargetsEnabled) {
  12429. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12430. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  12431. var renderTarget = this._renderTargets.data[renderIndex];
  12432. if (renderTarget._shouldRender()) {
  12433. this._renderId++;
  12434. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  12435. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  12436. }
  12437. }
  12438. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  12439. this._renderId++;
  12440. }
  12441. if (this._renderTargets.length > 0) {
  12442. engine.restoreDefaultFramebuffer();
  12443. }
  12444. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12445. // Prepare Frame
  12446. this.postProcessManager._prepareFrame();
  12447. var beforeRenderDate = BABYLON.Tools.Now;
  12448. // Backgrounds
  12449. if (this.layers.length) {
  12450. engine.setDepthBuffer(false);
  12451. var layerIndex;
  12452. var layer;
  12453. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12454. layer = this.layers[layerIndex];
  12455. if (layer.isBackground) {
  12456. layer.render();
  12457. }
  12458. }
  12459. engine.setDepthBuffer(true);
  12460. }
  12461. // Render
  12462. BABYLON.Tools.StartPerformanceCounter("Main render");
  12463. this._renderingManager.render(null, null, true, true);
  12464. BABYLON.Tools.EndPerformanceCounter("Main render");
  12465. // Bounding boxes
  12466. this._boundingBoxRenderer.render();
  12467. // Lens flares
  12468. if (this.lensFlaresEnabled) {
  12469. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12470. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  12471. this.lensFlareSystems[lensFlareSystemIndex].render();
  12472. }
  12473. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  12474. }
  12475. // Foregrounds
  12476. if (this.layers.length) {
  12477. engine.setDepthBuffer(false);
  12478. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  12479. layer = this.layers[layerIndex];
  12480. if (!layer.isBackground) {
  12481. layer.render();
  12482. }
  12483. }
  12484. engine.setDepthBuffer(true);
  12485. }
  12486. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  12487. // Finalize frame
  12488. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  12489. // Update camera
  12490. this.activeCamera._updateFromScene();
  12491. // Reset some special arrays
  12492. this._renderTargets.reset();
  12493. if (this.afterCameraRender) {
  12494. this.afterCameraRender(this.activeCamera);
  12495. }
  12496. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  12497. };
  12498. Scene.prototype._processSubCameras = function (camera) {
  12499. if (camera.subCameras.length === 0) {
  12500. this._renderForCamera(camera);
  12501. return;
  12502. }
  12503. for (var index = 0; index < camera.subCameras.length; index++) {
  12504. this._renderForCamera(camera.subCameras[index]);
  12505. }
  12506. this.activeCamera = camera;
  12507. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  12508. // Update camera
  12509. this.activeCamera._updateFromScene();
  12510. };
  12511. Scene.prototype._checkIntersections = function () {
  12512. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  12513. var sourceMesh = this._meshesForIntersections.data[index];
  12514. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  12515. var action = sourceMesh.actionManager.actions[actionIndex];
  12516. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12517. var parameters = action.getTriggerParameter();
  12518. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  12519. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  12520. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  12521. if (areIntersecting && currentIntersectionInProgress === -1) {
  12522. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  12523. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  12524. sourceMesh._intersectionsInProgress.push(otherMesh);
  12525. }
  12526. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12527. sourceMesh._intersectionsInProgress.push(otherMesh);
  12528. }
  12529. }
  12530. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  12531. //They intersected, and now they don't.
  12532. //is this trigger an exit trigger? execute an event.
  12533. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12534. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  12535. }
  12536. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  12537. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  12538. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  12539. }
  12540. }
  12541. }
  12542. }
  12543. }
  12544. };
  12545. Scene.prototype.render = function () {
  12546. var startDate = BABYLON.Tools.Now;
  12547. this._particlesDuration = 0;
  12548. this._spritesDuration = 0;
  12549. this._activeParticles = 0;
  12550. this._renderDuration = 0;
  12551. this._renderTargetsDuration = 0;
  12552. this._evaluateActiveMeshesDuration = 0;
  12553. this._totalVertices = 0;
  12554. this._activeIndices = 0;
  12555. this._activeBones = 0;
  12556. this.getEngine().resetDrawCalls();
  12557. this._meshesForIntersections.reset();
  12558. this.resetCachedMaterial();
  12559. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  12560. // Actions
  12561. if (this.actionManager) {
  12562. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  12563. }
  12564. //Simplification Queue
  12565. if (!this.simplificationQueue.running) {
  12566. this.simplificationQueue.executeNext();
  12567. }
  12568. // Before render
  12569. if (this.beforeRender) {
  12570. this.beforeRender();
  12571. }
  12572. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  12573. this._onBeforeRenderCallbacks[callbackIndex]();
  12574. }
  12575. // Animations
  12576. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  12577. this._animationRatio = deltaTime * (60.0 / 1000.0);
  12578. this._animate();
  12579. // Physics
  12580. if (this._physicsEngine) {
  12581. BABYLON.Tools.StartPerformanceCounter("Physics");
  12582. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  12583. BABYLON.Tools.EndPerformanceCounter("Physics");
  12584. }
  12585. // Customs render targets
  12586. var beforeRenderTargetDate = BABYLON.Tools.Now;
  12587. var engine = this.getEngine();
  12588. var currentActiveCamera = this.activeCamera;
  12589. if (this.renderTargetsEnabled) {
  12590. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12591. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  12592. var renderTarget = this.customRenderTargets[customIndex];
  12593. if (renderTarget._shouldRender()) {
  12594. this._renderId++;
  12595. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  12596. if (!this.activeCamera)
  12597. throw new Error("Active camera not set");
  12598. // Viewport
  12599. engine.setViewport(this.activeCamera.viewport);
  12600. // Camera
  12601. this.updateTransformMatrix();
  12602. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  12603. }
  12604. }
  12605. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  12606. this._renderId++;
  12607. }
  12608. if (this.customRenderTargets.length > 0) {
  12609. engine.restoreDefaultFramebuffer();
  12610. }
  12611. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  12612. this.activeCamera = currentActiveCamera;
  12613. // Procedural textures
  12614. if (this.proceduralTexturesEnabled) {
  12615. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12616. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  12617. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  12618. if (proceduralTexture._shouldRender()) {
  12619. proceduralTexture.render();
  12620. }
  12621. }
  12622. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  12623. }
  12624. // Clear
  12625. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  12626. // Shadows
  12627. if (this.shadowsEnabled) {
  12628. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  12629. var light = this.lights[lightIndex];
  12630. var shadowGenerator = light.getShadowGenerator();
  12631. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  12632. this._renderTargets.push(shadowGenerator.getShadowMap());
  12633. }
  12634. }
  12635. }
  12636. // Depth renderer
  12637. if (this._depthRenderer) {
  12638. this._renderTargets.push(this._depthRenderer.getDepthMap());
  12639. }
  12640. // RenderPipeline
  12641. this.postProcessRenderPipelineManager.update();
  12642. // Multi-cameras?
  12643. if (this.activeCameras.length > 0) {
  12644. var currentRenderId = this._renderId;
  12645. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  12646. this._renderId = currentRenderId;
  12647. this._processSubCameras(this.activeCameras[cameraIndex]);
  12648. }
  12649. }
  12650. else {
  12651. if (!this.activeCamera) {
  12652. throw new Error("No camera defined");
  12653. }
  12654. this._processSubCameras(this.activeCamera);
  12655. }
  12656. // Intersection checks
  12657. this._checkIntersections();
  12658. // Update the audio listener attached to the camera
  12659. this._updateAudioParameters();
  12660. // After render
  12661. if (this.afterRender) {
  12662. this.afterRender();
  12663. }
  12664. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  12665. this._onAfterRenderCallbacks[callbackIndex]();
  12666. }
  12667. for (var index = 0; index < this._toBeDisposed.length; index++) {
  12668. this._toBeDisposed.data[index].dispose();
  12669. this._toBeDisposed[index] = null;
  12670. }
  12671. this._toBeDisposed.reset();
  12672. if (this.dumpNextRenderTargets) {
  12673. this.dumpNextRenderTargets = false;
  12674. }
  12675. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  12676. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  12677. };
  12678. Scene.prototype._updateAudioParameters = function () {
  12679. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  12680. return;
  12681. }
  12682. var listeningCamera;
  12683. var audioEngine = BABYLON.Engine.audioEngine;
  12684. if (this.activeCameras.length > 0) {
  12685. listeningCamera = this.activeCameras[0];
  12686. }
  12687. else {
  12688. listeningCamera = this.activeCamera;
  12689. }
  12690. if (listeningCamera && audioEngine.canUseWebAudio) {
  12691. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  12692. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  12693. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  12694. cameraDirection.normalize();
  12695. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  12696. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12697. var sound = this.mainSoundTrack.soundCollection[i];
  12698. if (sound.useCustomAttenuation) {
  12699. sound.updateDistanceFromListener();
  12700. }
  12701. }
  12702. for (i = 0; i < this.soundTracks.length; i++) {
  12703. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12704. sound = this.soundTracks[i].soundCollection[j];
  12705. if (sound.useCustomAttenuation) {
  12706. sound.updateDistanceFromListener();
  12707. }
  12708. }
  12709. }
  12710. }
  12711. };
  12712. Object.defineProperty(Scene.prototype, "audioEnabled", {
  12713. // Audio
  12714. get: function () {
  12715. return this._audioEnabled;
  12716. },
  12717. set: function (value) {
  12718. this._audioEnabled = value;
  12719. if (this._audioEnabled) {
  12720. this._enableAudio();
  12721. }
  12722. else {
  12723. this._disableAudio();
  12724. }
  12725. },
  12726. enumerable: true,
  12727. configurable: true
  12728. });
  12729. Scene.prototype._disableAudio = function () {
  12730. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12731. this.mainSoundTrack.soundCollection[i].pause();
  12732. }
  12733. for (i = 0; i < this.soundTracks.length; i++) {
  12734. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12735. this.soundTracks[i].soundCollection[j].pause();
  12736. }
  12737. }
  12738. };
  12739. Scene.prototype._enableAudio = function () {
  12740. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  12741. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  12742. this.mainSoundTrack.soundCollection[i].play();
  12743. }
  12744. }
  12745. for (i = 0; i < this.soundTracks.length; i++) {
  12746. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  12747. if (this.soundTracks[i].soundCollection[j].isPaused) {
  12748. this.soundTracks[i].soundCollection[j].play();
  12749. }
  12750. }
  12751. }
  12752. };
  12753. Object.defineProperty(Scene.prototype, "headphone", {
  12754. get: function () {
  12755. return this._headphone;
  12756. },
  12757. set: function (value) {
  12758. this._headphone = value;
  12759. if (this._headphone) {
  12760. this._switchAudioModeForHeadphones();
  12761. }
  12762. else {
  12763. this._switchAudioModeForNormalSpeakers();
  12764. }
  12765. },
  12766. enumerable: true,
  12767. configurable: true
  12768. });
  12769. Scene.prototype._switchAudioModeForHeadphones = function () {
  12770. this.mainSoundTrack.switchPanningModelToHRTF();
  12771. for (var i = 0; i < this.soundTracks.length; i++) {
  12772. this.soundTracks[i].switchPanningModelToHRTF();
  12773. }
  12774. };
  12775. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  12776. this.mainSoundTrack.switchPanningModelToEqualPower();
  12777. for (var i = 0; i < this.soundTracks.length; i++) {
  12778. this.soundTracks[i].switchPanningModelToEqualPower();
  12779. }
  12780. };
  12781. Scene.prototype.enableDepthRenderer = function () {
  12782. if (this._depthRenderer) {
  12783. return this._depthRenderer;
  12784. }
  12785. this._depthRenderer = new BABYLON.DepthRenderer(this);
  12786. return this._depthRenderer;
  12787. };
  12788. Scene.prototype.disableDepthRenderer = function () {
  12789. if (!this._depthRenderer) {
  12790. return;
  12791. }
  12792. this._depthRenderer.dispose();
  12793. this._depthRenderer = null;
  12794. };
  12795. Scene.prototype.dispose = function () {
  12796. this.beforeRender = null;
  12797. this.afterRender = null;
  12798. this.skeletons = [];
  12799. this._boundingBoxRenderer.dispose();
  12800. if (this._depthRenderer) {
  12801. this._depthRenderer.dispose();
  12802. }
  12803. // Debug layer
  12804. this.debugLayer.hide();
  12805. // Events
  12806. if (this.onDispose) {
  12807. this.onDispose();
  12808. }
  12809. this._onBeforeRenderCallbacks = [];
  12810. this._onAfterRenderCallbacks = [];
  12811. this.detachControl();
  12812. // Release sounds & sounds tracks
  12813. this.disposeSounds();
  12814. // Detach cameras
  12815. var canvas = this._engine.getRenderingCanvas();
  12816. var index;
  12817. for (index = 0; index < this.cameras.length; index++) {
  12818. this.cameras[index].detachControl(canvas);
  12819. }
  12820. while (this.lights.length) {
  12821. this.lights[0].dispose();
  12822. }
  12823. while (this.meshes.length) {
  12824. this.meshes[0].dispose(true);
  12825. }
  12826. while (this.cameras.length) {
  12827. this.cameras[0].dispose();
  12828. }
  12829. while (this.materials.length) {
  12830. this.materials[0].dispose();
  12831. }
  12832. while (this.particleSystems.length) {
  12833. this.particleSystems[0].dispose();
  12834. }
  12835. while (this.spriteManagers.length) {
  12836. this.spriteManagers[0].dispose();
  12837. }
  12838. while (this.layers.length) {
  12839. this.layers[0].dispose();
  12840. }
  12841. while (this.textures.length) {
  12842. this.textures[0].dispose();
  12843. }
  12844. // Post-processes
  12845. this.postProcessManager.dispose();
  12846. // Physics
  12847. if (this._physicsEngine) {
  12848. this.disablePhysicsEngine();
  12849. }
  12850. // Remove from engine
  12851. index = this._engine.scenes.indexOf(this);
  12852. if (index > -1) {
  12853. this._engine.scenes.splice(index, 1);
  12854. }
  12855. this._engine.wipeCaches();
  12856. };
  12857. // Release sounds & sounds tracks
  12858. Scene.prototype.disposeSounds = function () {
  12859. this.mainSoundTrack.dispose();
  12860. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  12861. this.soundTracks[scIndex].dispose();
  12862. }
  12863. };
  12864. // Octrees
  12865. Scene.prototype.getWorldExtends = function () {
  12866. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12867. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  12868. for (var index = 0; index < this.meshes.length; index++) {
  12869. var mesh = this.meshes[index];
  12870. mesh.computeWorldMatrix(true);
  12871. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  12872. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  12873. BABYLON.Tools.CheckExtends(minBox, min, max);
  12874. BABYLON.Tools.CheckExtends(maxBox, min, max);
  12875. }
  12876. return {
  12877. min: min,
  12878. max: max
  12879. };
  12880. };
  12881. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  12882. if (maxCapacity === void 0) { maxCapacity = 64; }
  12883. if (maxDepth === void 0) { maxDepth = 2; }
  12884. if (!this._selectionOctree) {
  12885. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  12886. }
  12887. var worldExtends = this.getWorldExtends();
  12888. // Update octree
  12889. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  12890. return this._selectionOctree;
  12891. };
  12892. // Picking
  12893. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  12894. var engine = this._engine;
  12895. if (!camera) {
  12896. if (!this.activeCamera)
  12897. throw new Error("Active camera not set");
  12898. camera = this.activeCamera;
  12899. }
  12900. var cameraViewport = camera.viewport;
  12901. var viewport = cameraViewport.toGlobal(engine);
  12902. // Moving coordinates to local viewport world
  12903. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  12904. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  12905. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  12906. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  12907. };
  12908. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  12909. var pickingInfo = null;
  12910. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  12911. var mesh = this.meshes[meshIndex];
  12912. if (predicate) {
  12913. if (!predicate(mesh)) {
  12914. continue;
  12915. }
  12916. }
  12917. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  12918. continue;
  12919. }
  12920. var world = mesh.getWorldMatrix();
  12921. var ray = rayFunction(world);
  12922. var result = mesh.intersects(ray, fastCheck);
  12923. if (!result || !result.hit)
  12924. continue;
  12925. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  12926. continue;
  12927. pickingInfo = result;
  12928. if (fastCheck) {
  12929. break;
  12930. }
  12931. }
  12932. return pickingInfo || new BABYLON.PickingInfo();
  12933. };
  12934. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  12935. var _this = this;
  12936. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  12937. /// <param name="x">X position on screen</param>
  12938. /// <param name="y">Y position on screen</param>
  12939. /// <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>
  12940. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  12941. /// <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>
  12942. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  12943. };
  12944. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  12945. var _this = this;
  12946. return this._internalPick(function (world) {
  12947. if (!_this._pickWithRayInverseMatrix) {
  12948. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  12949. }
  12950. world.invertToRef(_this._pickWithRayInverseMatrix);
  12951. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  12952. }, predicate, fastCheck);
  12953. };
  12954. Scene.prototype.setPointerOverMesh = function (mesh) {
  12955. if (this._pointerOverMesh === mesh) {
  12956. return;
  12957. }
  12958. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  12959. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  12960. }
  12961. this._pointerOverMesh = mesh;
  12962. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  12963. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  12964. }
  12965. };
  12966. Scene.prototype.getPointerOverMesh = function () {
  12967. return this._pointerOverMesh;
  12968. };
  12969. // Physics
  12970. Scene.prototype.getPhysicsEngine = function () {
  12971. return this._physicsEngine;
  12972. };
  12973. Scene.prototype.enablePhysics = function (gravity, plugin) {
  12974. if (this._physicsEngine) {
  12975. return true;
  12976. }
  12977. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  12978. if (!this._physicsEngine.isSupported()) {
  12979. this._physicsEngine = null;
  12980. return false;
  12981. }
  12982. this._physicsEngine._initialize(gravity);
  12983. return true;
  12984. };
  12985. Scene.prototype.disablePhysicsEngine = function () {
  12986. if (!this._physicsEngine) {
  12987. return;
  12988. }
  12989. this._physicsEngine.dispose();
  12990. this._physicsEngine = undefined;
  12991. };
  12992. Scene.prototype.isPhysicsEnabled = function () {
  12993. return this._physicsEngine !== undefined;
  12994. };
  12995. Scene.prototype.setGravity = function (gravity) {
  12996. if (!this._physicsEngine) {
  12997. return;
  12998. }
  12999. this._physicsEngine._setGravity(gravity);
  13000. };
  13001. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13002. if (parts.parts) {
  13003. options = parts;
  13004. parts = parts.parts;
  13005. }
  13006. if (!this._physicsEngine) {
  13007. return null;
  13008. }
  13009. for (var index = 0; index < parts.length; index++) {
  13010. var mesh = parts[index].mesh;
  13011. mesh._physicImpostor = parts[index].impostor;
  13012. mesh._physicsMass = options.mass / parts.length;
  13013. mesh._physicsFriction = options.friction;
  13014. mesh._physicRestitution = options.restitution;
  13015. }
  13016. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13017. };
  13018. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13019. for (var index = 0; index < compound.parts.length; index++) {
  13020. var mesh = compound.parts[index].mesh;
  13021. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13022. this._physicsEngine._unregisterMesh(mesh);
  13023. }
  13024. };
  13025. // Misc.
  13026. Scene.prototype.createDefaultCameraOrLight = function () {
  13027. // Light
  13028. if (this.lights.length === 0) {
  13029. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13030. }
  13031. // Camera
  13032. if (!this.activeCamera) {
  13033. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13034. // Compute position
  13035. var worldExtends = this.getWorldExtends();
  13036. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13037. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13038. camera.setTarget(worldCenter);
  13039. this.activeCamera = camera;
  13040. }
  13041. };
  13042. // Tags
  13043. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13044. if (tagsQuery === undefined) {
  13045. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13046. return list;
  13047. }
  13048. var listByTags = [];
  13049. forEach = forEach || (function (item) {
  13050. return;
  13051. });
  13052. for (var i in list) {
  13053. var item = list[i];
  13054. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13055. listByTags.push(item);
  13056. forEach(item);
  13057. }
  13058. }
  13059. return listByTags;
  13060. };
  13061. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13062. return this._getByTags(this.meshes, tagsQuery, forEach);
  13063. };
  13064. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13065. return this._getByTags(this.cameras, tagsQuery, forEach);
  13066. };
  13067. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13068. return this._getByTags(this.lights, tagsQuery, forEach);
  13069. };
  13070. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13071. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13072. };
  13073. // Statics
  13074. Scene._FOGMODE_NONE = 0;
  13075. Scene._FOGMODE_EXP = 1;
  13076. Scene._FOGMODE_EXP2 = 2;
  13077. Scene._FOGMODE_LINEAR = 3;
  13078. Scene.MinDeltaTime = 1.0;
  13079. Scene.MaxDeltaTime = 1000.0;
  13080. return Scene;
  13081. })();
  13082. BABYLON.Scene = Scene;
  13083. })(BABYLON || (BABYLON = {}));
  13084. //# sourceMappingURL=babylon.scene.js.map
  13085. var BABYLON;
  13086. (function (BABYLON) {
  13087. var VertexBuffer = (function () {
  13088. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13089. if (engine instanceof BABYLON.Mesh) {
  13090. this._engine = engine.getScene().getEngine();
  13091. }
  13092. else {
  13093. this._engine = engine;
  13094. }
  13095. this._updatable = updatable;
  13096. this._data = data;
  13097. if (!postponeInternalCreation) {
  13098. this.create();
  13099. }
  13100. this._kind = kind;
  13101. if (stride) {
  13102. this._strideSize = stride;
  13103. return;
  13104. }
  13105. switch (kind) {
  13106. case VertexBuffer.PositionKind:
  13107. this._strideSize = 3;
  13108. break;
  13109. case VertexBuffer.NormalKind:
  13110. this._strideSize = 3;
  13111. break;
  13112. case VertexBuffer.UVKind:
  13113. this._strideSize = 2;
  13114. break;
  13115. case VertexBuffer.UV2Kind:
  13116. this._strideSize = 2;
  13117. break;
  13118. case VertexBuffer.ColorKind:
  13119. this._strideSize = 4;
  13120. break;
  13121. case VertexBuffer.MatricesIndicesKind:
  13122. this._strideSize = 4;
  13123. break;
  13124. case VertexBuffer.MatricesWeightsKind:
  13125. this._strideSize = 4;
  13126. break;
  13127. }
  13128. }
  13129. // Properties
  13130. VertexBuffer.prototype.isUpdatable = function () {
  13131. return this._updatable;
  13132. };
  13133. VertexBuffer.prototype.getData = function () {
  13134. return this._data;
  13135. };
  13136. VertexBuffer.prototype.getBuffer = function () {
  13137. return this._buffer;
  13138. };
  13139. VertexBuffer.prototype.getStrideSize = function () {
  13140. return this._strideSize;
  13141. };
  13142. // Methods
  13143. VertexBuffer.prototype.create = function (data) {
  13144. if (!data && this._buffer) {
  13145. return; // nothing to do
  13146. }
  13147. data = data || this._data;
  13148. if (!this._buffer) {
  13149. if (this._updatable) {
  13150. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13151. }
  13152. else {
  13153. this._buffer = this._engine.createVertexBuffer(data);
  13154. }
  13155. }
  13156. if (this._updatable) {
  13157. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13158. this._data = data;
  13159. }
  13160. };
  13161. VertexBuffer.prototype.update = function (data) {
  13162. this.create(data);
  13163. };
  13164. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13165. if (!this._buffer) {
  13166. return;
  13167. }
  13168. if (this._updatable) {
  13169. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13170. this._data = null;
  13171. }
  13172. };
  13173. VertexBuffer.prototype.dispose = function () {
  13174. if (!this._buffer) {
  13175. return;
  13176. }
  13177. if (this._engine._releaseBuffer(this._buffer)) {
  13178. this._buffer = null;
  13179. }
  13180. };
  13181. Object.defineProperty(VertexBuffer, "PositionKind", {
  13182. get: function () {
  13183. return VertexBuffer._PositionKind;
  13184. },
  13185. enumerable: true,
  13186. configurable: true
  13187. });
  13188. Object.defineProperty(VertexBuffer, "NormalKind", {
  13189. get: function () {
  13190. return VertexBuffer._NormalKind;
  13191. },
  13192. enumerable: true,
  13193. configurable: true
  13194. });
  13195. Object.defineProperty(VertexBuffer, "UVKind", {
  13196. get: function () {
  13197. return VertexBuffer._UVKind;
  13198. },
  13199. enumerable: true,
  13200. configurable: true
  13201. });
  13202. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13203. get: function () {
  13204. return VertexBuffer._UV2Kind;
  13205. },
  13206. enumerable: true,
  13207. configurable: true
  13208. });
  13209. Object.defineProperty(VertexBuffer, "ColorKind", {
  13210. get: function () {
  13211. return VertexBuffer._ColorKind;
  13212. },
  13213. enumerable: true,
  13214. configurable: true
  13215. });
  13216. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13217. get: function () {
  13218. return VertexBuffer._MatricesIndicesKind;
  13219. },
  13220. enumerable: true,
  13221. configurable: true
  13222. });
  13223. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13224. get: function () {
  13225. return VertexBuffer._MatricesWeightsKind;
  13226. },
  13227. enumerable: true,
  13228. configurable: true
  13229. });
  13230. // Enums
  13231. VertexBuffer._PositionKind = "position";
  13232. VertexBuffer._NormalKind = "normal";
  13233. VertexBuffer._UVKind = "uv";
  13234. VertexBuffer._UV2Kind = "uv2";
  13235. VertexBuffer._ColorKind = "color";
  13236. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13237. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13238. return VertexBuffer;
  13239. })();
  13240. BABYLON.VertexBuffer = VertexBuffer;
  13241. })(BABYLON || (BABYLON = {}));
  13242. //# sourceMappingURL=babylon.vertexBuffer.js.map
  13243. var __extends = this.__extends || function (d, b) {
  13244. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13245. function __() { this.constructor = d; }
  13246. __.prototype = b.prototype;
  13247. d.prototype = new __();
  13248. };
  13249. var BABYLON;
  13250. (function (BABYLON) {
  13251. /**
  13252. * Creates an instance based on a source mesh.
  13253. */
  13254. var InstancedMesh = (function (_super) {
  13255. __extends(InstancedMesh, _super);
  13256. function InstancedMesh(name, source) {
  13257. _super.call(this, name, source.getScene());
  13258. source.instances.push(this);
  13259. this._sourceMesh = source;
  13260. this.position.copyFrom(source.position);
  13261. this.rotation.copyFrom(source.rotation);
  13262. this.scaling.copyFrom(source.scaling);
  13263. if (source.rotationQuaternion) {
  13264. this.rotationQuaternion = source.rotationQuaternion.clone();
  13265. }
  13266. this.infiniteDistance = source.infiniteDistance;
  13267. this.setPivotMatrix(source.getPivotMatrix());
  13268. this.refreshBoundingInfo();
  13269. this._syncSubMeshes();
  13270. }
  13271. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13272. // Methods
  13273. get: function () {
  13274. return this._sourceMesh.receiveShadows;
  13275. },
  13276. enumerable: true,
  13277. configurable: true
  13278. });
  13279. Object.defineProperty(InstancedMesh.prototype, "material", {
  13280. get: function () {
  13281. return this._sourceMesh.material;
  13282. },
  13283. enumerable: true,
  13284. configurable: true
  13285. });
  13286. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13287. get: function () {
  13288. return this._sourceMesh.visibility;
  13289. },
  13290. enumerable: true,
  13291. configurable: true
  13292. });
  13293. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13294. get: function () {
  13295. return this._sourceMesh.skeleton;
  13296. },
  13297. enumerable: true,
  13298. configurable: true
  13299. });
  13300. InstancedMesh.prototype.getTotalVertices = function () {
  13301. return this._sourceMesh.getTotalVertices();
  13302. };
  13303. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13304. get: function () {
  13305. return this._sourceMesh;
  13306. },
  13307. enumerable: true,
  13308. configurable: true
  13309. });
  13310. InstancedMesh.prototype.getVerticesData = function (kind) {
  13311. return this._sourceMesh.getVerticesData(kind);
  13312. };
  13313. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13314. return this._sourceMesh.isVerticesDataPresent(kind);
  13315. };
  13316. InstancedMesh.prototype.getIndices = function () {
  13317. return this._sourceMesh.getIndices();
  13318. };
  13319. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13320. get: function () {
  13321. return this._sourceMesh._positions;
  13322. },
  13323. enumerable: true,
  13324. configurable: true
  13325. });
  13326. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13327. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13328. if (data) {
  13329. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  13330. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  13331. }
  13332. this._updateBoundingInfo();
  13333. };
  13334. InstancedMesh.prototype._preActivate = function () {
  13335. if (this._currentLOD) {
  13336. this._currentLOD._preActivate();
  13337. }
  13338. };
  13339. InstancedMesh.prototype._activate = function (renderId) {
  13340. if (this._currentLOD) {
  13341. this._currentLOD._registerInstanceForRenderId(this, renderId);
  13342. }
  13343. };
  13344. InstancedMesh.prototype.getLOD = function (camera) {
  13345. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13346. if (this._currentLOD === this.sourceMesh) {
  13347. return this;
  13348. }
  13349. return this._currentLOD;
  13350. };
  13351. InstancedMesh.prototype._syncSubMeshes = function () {
  13352. this.releaseSubMeshes();
  13353. if (this._sourceMesh.subMeshes) {
  13354. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13355. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13356. }
  13357. }
  13358. };
  13359. InstancedMesh.prototype._generatePointsArray = function () {
  13360. return this._sourceMesh._generatePointsArray();
  13361. };
  13362. // Clone
  13363. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13364. var result = this._sourceMesh.createInstance(name);
  13365. // Deep copy
  13366. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  13367. // Bounding info
  13368. this.refreshBoundingInfo();
  13369. // Parent
  13370. if (newParent) {
  13371. result.parent = newParent;
  13372. }
  13373. if (!doNotCloneChildren) {
  13374. for (var index = 0; index < this.getScene().meshes.length; index++) {
  13375. var mesh = this.getScene().meshes[index];
  13376. if (mesh.parent === this) {
  13377. mesh.clone(mesh.name, result);
  13378. }
  13379. }
  13380. }
  13381. result.computeWorldMatrix(true);
  13382. return result;
  13383. };
  13384. // Dispoe
  13385. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  13386. // Remove from mesh
  13387. var index = this._sourceMesh.instances.indexOf(this);
  13388. this._sourceMesh.instances.splice(index, 1);
  13389. _super.prototype.dispose.call(this, doNotRecurse);
  13390. };
  13391. return InstancedMesh;
  13392. })(BABYLON.AbstractMesh);
  13393. BABYLON.InstancedMesh = InstancedMesh;
  13394. })(BABYLON || (BABYLON = {}));
  13395. //# sourceMappingURL=babylon.instancedMesh.js.map
  13396. var __extends = this.__extends || function (d, b) {
  13397. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13398. function __() { this.constructor = d; }
  13399. __.prototype = b.prototype;
  13400. d.prototype = new __();
  13401. };
  13402. var BABYLON;
  13403. (function (BABYLON) {
  13404. var _InstancesBatch = (function () {
  13405. function _InstancesBatch() {
  13406. this.mustReturn = false;
  13407. this.visibleInstances = new Array();
  13408. this.renderSelf = new Array();
  13409. }
  13410. return _InstancesBatch;
  13411. })();
  13412. BABYLON._InstancesBatch = _InstancesBatch;
  13413. var Mesh = (function (_super) {
  13414. __extends(Mesh, _super);
  13415. /**
  13416. * @constructor
  13417. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  13418. * @param {Scene} scene - The scene to add this mesh to.
  13419. * @param {Node} parent - The parent of this mesh, if it has one
  13420. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  13421. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  13422. * When false, achieved by calling a clone(), also passing False.
  13423. * This will make creation of children, recursive.
  13424. */
  13425. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  13426. if (parent === void 0) { parent = null; }
  13427. _super.call(this, name, scene);
  13428. // Members
  13429. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  13430. this.instances = new Array();
  13431. this._LODLevels = new Array();
  13432. this._onBeforeRenderCallbacks = new Array();
  13433. this._onAfterRenderCallbacks = new Array();
  13434. this._visibleInstances = {};
  13435. this._renderIdForInstances = new Array();
  13436. this._batchCache = new _InstancesBatch();
  13437. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  13438. this._sideOrientation = Mesh._DEFAULTSIDE;
  13439. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  13440. if (source) {
  13441. // Geometry
  13442. if (source._geometry) {
  13443. source._geometry.applyToMesh(this);
  13444. }
  13445. // Deep copy
  13446. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  13447. // Material
  13448. this.material = source.material;
  13449. if (!doNotCloneChildren) {
  13450. for (var index = 0; index < scene.meshes.length; index++) {
  13451. var mesh = scene.meshes[index];
  13452. if (mesh.parent === source) {
  13453. // doNotCloneChildren is always going to be False
  13454. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  13455. }
  13456. }
  13457. }
  13458. for (index = 0; index < scene.particleSystems.length; index++) {
  13459. var system = scene.particleSystems[index];
  13460. if (system.emitter === source) {
  13461. system.clone(system.name, this);
  13462. }
  13463. }
  13464. this.computeWorldMatrix(true);
  13465. }
  13466. // Parent
  13467. if (parent !== null) {
  13468. this.parent = parent;
  13469. }
  13470. }
  13471. Object.defineProperty(Mesh, "FRONTSIDE", {
  13472. get: function () {
  13473. return Mesh._FRONTSIDE;
  13474. },
  13475. enumerable: true,
  13476. configurable: true
  13477. });
  13478. Object.defineProperty(Mesh, "BACKSIDE", {
  13479. get: function () {
  13480. return Mesh._BACKSIDE;
  13481. },
  13482. enumerable: true,
  13483. configurable: true
  13484. });
  13485. Object.defineProperty(Mesh, "DOUBLESIDE", {
  13486. get: function () {
  13487. return Mesh._DOUBLESIDE;
  13488. },
  13489. enumerable: true,
  13490. configurable: true
  13491. });
  13492. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  13493. get: function () {
  13494. return Mesh._DEFAULTSIDE;
  13495. },
  13496. enumerable: true,
  13497. configurable: true
  13498. });
  13499. Object.defineProperty(Mesh, "NO_CAP", {
  13500. get: function () {
  13501. return Mesh._NO_CAP;
  13502. },
  13503. enumerable: true,
  13504. configurable: true
  13505. });
  13506. Object.defineProperty(Mesh, "CAP_START", {
  13507. get: function () {
  13508. return Mesh._CAP_START;
  13509. },
  13510. enumerable: true,
  13511. configurable: true
  13512. });
  13513. Object.defineProperty(Mesh, "CAP_END", {
  13514. get: function () {
  13515. return Mesh._CAP_END;
  13516. },
  13517. enumerable: true,
  13518. configurable: true
  13519. });
  13520. Object.defineProperty(Mesh, "CAP_ALL", {
  13521. get: function () {
  13522. return Mesh._CAP_ALL;
  13523. },
  13524. enumerable: true,
  13525. configurable: true
  13526. });
  13527. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  13528. // Methods
  13529. get: function () {
  13530. return this._LODLevels.length > 0;
  13531. },
  13532. enumerable: true,
  13533. configurable: true
  13534. });
  13535. Mesh.prototype._sortLODLevels = function () {
  13536. this._LODLevels.sort(function (a, b) {
  13537. if (a.distance < b.distance) {
  13538. return 1;
  13539. }
  13540. if (a.distance > b.distance) {
  13541. return -1;
  13542. }
  13543. return 0;
  13544. });
  13545. };
  13546. /**
  13547. * Add a mesh as LOD level triggered at the given distance.
  13548. * @param {number} distance - the distance from the center of the object to show this level
  13549. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  13550. * @return {BABYLON.Mesh} this mesh (for chaining)
  13551. */
  13552. Mesh.prototype.addLODLevel = function (distance, mesh) {
  13553. if (mesh && mesh._masterMesh) {
  13554. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  13555. return this;
  13556. }
  13557. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  13558. this._LODLevels.push(level);
  13559. if (mesh) {
  13560. mesh._masterMesh = this;
  13561. }
  13562. this._sortLODLevels();
  13563. return this;
  13564. };
  13565. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  13566. for (var index = 0; index < this._LODLevels.length; index++) {
  13567. var level = this._LODLevels[index];
  13568. if (level.distance === distance) {
  13569. return level.mesh;
  13570. }
  13571. }
  13572. return null;
  13573. };
  13574. /**
  13575. * Remove a mesh from the LOD array
  13576. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  13577. * @return {BABYLON.Mesh} this mesh (for chaining)
  13578. */
  13579. Mesh.prototype.removeLODLevel = function (mesh) {
  13580. for (var index = 0; index < this._LODLevels.length; index++) {
  13581. if (this._LODLevels[index].mesh === mesh) {
  13582. this._LODLevels.splice(index, 1);
  13583. if (mesh) {
  13584. mesh._masterMesh = null;
  13585. }
  13586. }
  13587. }
  13588. this._sortLODLevels();
  13589. return this;
  13590. };
  13591. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  13592. if (!this._LODLevels || this._LODLevels.length === 0) {
  13593. return this;
  13594. }
  13595. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  13596. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  13597. if (this.onLODLevelSelection) {
  13598. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  13599. }
  13600. return this;
  13601. }
  13602. for (var index = 0; index < this._LODLevels.length; index++) {
  13603. var level = this._LODLevels[index];
  13604. if (level.distance < distanceToCamera) {
  13605. if (level.mesh) {
  13606. level.mesh._preActivate();
  13607. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  13608. }
  13609. if (this.onLODLevelSelection) {
  13610. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  13611. }
  13612. return level.mesh;
  13613. }
  13614. }
  13615. if (this.onLODLevelSelection) {
  13616. this.onLODLevelSelection(distanceToCamera, this, this);
  13617. }
  13618. return this;
  13619. };
  13620. Object.defineProperty(Mesh.prototype, "geometry", {
  13621. get: function () {
  13622. return this._geometry;
  13623. },
  13624. enumerable: true,
  13625. configurable: true
  13626. });
  13627. Mesh.prototype.getTotalVertices = function () {
  13628. if (!this._geometry) {
  13629. return 0;
  13630. }
  13631. return this._geometry.getTotalVertices();
  13632. };
  13633. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  13634. if (!this._geometry) {
  13635. return null;
  13636. }
  13637. return this._geometry.getVerticesData(kind, copyWhenShared);
  13638. };
  13639. Mesh.prototype.getVertexBuffer = function (kind) {
  13640. if (!this._geometry) {
  13641. return undefined;
  13642. }
  13643. return this._geometry.getVertexBuffer(kind);
  13644. };
  13645. Mesh.prototype.isVerticesDataPresent = function (kind) {
  13646. if (!this._geometry) {
  13647. if (this._delayInfo) {
  13648. return this._delayInfo.indexOf(kind) !== -1;
  13649. }
  13650. return false;
  13651. }
  13652. return this._geometry.isVerticesDataPresent(kind);
  13653. };
  13654. Mesh.prototype.getVerticesDataKinds = function () {
  13655. if (!this._geometry) {
  13656. var result = [];
  13657. if (this._delayInfo) {
  13658. for (var kind in this._delayInfo) {
  13659. result.push(kind);
  13660. }
  13661. }
  13662. return result;
  13663. }
  13664. return this._geometry.getVerticesDataKinds();
  13665. };
  13666. Mesh.prototype.getTotalIndices = function () {
  13667. if (!this._geometry) {
  13668. return 0;
  13669. }
  13670. return this._geometry.getTotalIndices();
  13671. };
  13672. Mesh.prototype.getIndices = function (copyWhenShared) {
  13673. if (!this._geometry) {
  13674. return [];
  13675. }
  13676. return this._geometry.getIndices(copyWhenShared);
  13677. };
  13678. Object.defineProperty(Mesh.prototype, "isBlocked", {
  13679. get: function () {
  13680. return this._masterMesh !== null && this._masterMesh !== undefined;
  13681. },
  13682. enumerable: true,
  13683. configurable: true
  13684. });
  13685. Mesh.prototype.isReady = function () {
  13686. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  13687. return false;
  13688. }
  13689. return _super.prototype.isReady.call(this);
  13690. };
  13691. Mesh.prototype.isDisposed = function () {
  13692. return this._isDisposed;
  13693. };
  13694. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  13695. get: function () {
  13696. return this._sideOrientation;
  13697. },
  13698. set: function (sideO) {
  13699. this._sideOrientation = sideO;
  13700. },
  13701. enumerable: true,
  13702. configurable: true
  13703. });
  13704. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  13705. get: function () {
  13706. return this._areNormalsFrozen;
  13707. },
  13708. enumerable: true,
  13709. configurable: true
  13710. });
  13711. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  13712. Mesh.prototype.freezeNormals = function () {
  13713. this._areNormalsFrozen = true;
  13714. };
  13715. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  13716. Mesh.prototype.unfreezeNormals = function () {
  13717. this._areNormalsFrozen = false;
  13718. };
  13719. // Methods
  13720. Mesh.prototype._preActivate = function () {
  13721. var sceneRenderId = this.getScene().getRenderId();
  13722. if (this._preActivateId === sceneRenderId) {
  13723. return;
  13724. }
  13725. this._preActivateId = sceneRenderId;
  13726. this._visibleInstances = null;
  13727. };
  13728. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  13729. if (!this._visibleInstances) {
  13730. this._visibleInstances = {};
  13731. this._visibleInstances.defaultRenderId = renderId;
  13732. this._visibleInstances.selfDefaultRenderId = this._renderId;
  13733. }
  13734. if (!this._visibleInstances[renderId]) {
  13735. this._visibleInstances[renderId] = new Array();
  13736. }
  13737. this._visibleInstances[renderId].push(instance);
  13738. };
  13739. Mesh.prototype.refreshBoundingInfo = function () {
  13740. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13741. if (data) {
  13742. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  13743. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  13744. }
  13745. if (this.subMeshes) {
  13746. for (var index = 0; index < this.subMeshes.length; index++) {
  13747. this.subMeshes[index].refreshBoundingInfo();
  13748. }
  13749. }
  13750. this._updateBoundingInfo();
  13751. };
  13752. Mesh.prototype._createGlobalSubMesh = function () {
  13753. var totalVertices = this.getTotalVertices();
  13754. if (!totalVertices || !this.getIndices()) {
  13755. return null;
  13756. }
  13757. this.releaseSubMeshes();
  13758. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  13759. };
  13760. Mesh.prototype.subdivide = function (count) {
  13761. if (count < 1) {
  13762. return;
  13763. }
  13764. var totalIndices = this.getTotalIndices();
  13765. var subdivisionSize = (totalIndices / count) | 0;
  13766. var offset = 0;
  13767. while (subdivisionSize % 3 !== 0) {
  13768. subdivisionSize++;
  13769. }
  13770. this.releaseSubMeshes();
  13771. for (var index = 0; index < count; index++) {
  13772. if (offset >= totalIndices) {
  13773. break;
  13774. }
  13775. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  13776. offset += subdivisionSize;
  13777. }
  13778. this.synchronizeInstances();
  13779. };
  13780. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13781. if (kind instanceof Array) {
  13782. var temp = data;
  13783. data = kind;
  13784. kind = temp;
  13785. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  13786. }
  13787. if (!this._geometry) {
  13788. var vertexData = new BABYLON.VertexData();
  13789. vertexData.set(data, kind);
  13790. var scene = this.getScene();
  13791. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  13792. }
  13793. else {
  13794. this._geometry.setVerticesData(kind, data, updatable, stride);
  13795. }
  13796. };
  13797. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13798. if (!this._geometry) {
  13799. return;
  13800. }
  13801. if (!makeItUnique) {
  13802. this._geometry.updateVerticesData(kind, data, updateExtends);
  13803. }
  13804. else {
  13805. this.makeGeometryUnique();
  13806. this.updateVerticesData(kind, data, updateExtends, false);
  13807. }
  13808. };
  13809. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  13810. if (!this._geometry) {
  13811. return;
  13812. }
  13813. if (!makeItUnique) {
  13814. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  13815. }
  13816. else {
  13817. this.makeGeometryUnique();
  13818. this.updateVerticesDataDirectly(kind, data, offset, false);
  13819. }
  13820. };
  13821. // Mesh positions update function :
  13822. // updates the mesh positions according to the positionFunction returned values.
  13823. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  13824. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  13825. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  13826. if (computeNormals === void 0) { computeNormals = true; }
  13827. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13828. positionFunction(positions);
  13829. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  13830. if (computeNormals) {
  13831. var indices = this.getIndices();
  13832. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13833. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  13834. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  13835. }
  13836. };
  13837. Mesh.prototype.makeGeometryUnique = function () {
  13838. if (!this._geometry) {
  13839. return;
  13840. }
  13841. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  13842. geometry.applyToMesh(this);
  13843. };
  13844. Mesh.prototype.setIndices = function (indices, totalVertices) {
  13845. if (!this._geometry) {
  13846. var vertexData = new BABYLON.VertexData();
  13847. vertexData.indices = indices;
  13848. var scene = this.getScene();
  13849. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  13850. }
  13851. else {
  13852. this._geometry.setIndices(indices, totalVertices);
  13853. }
  13854. };
  13855. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  13856. var engine = this.getScene().getEngine();
  13857. // Wireframe
  13858. var indexToBind;
  13859. switch (fillMode) {
  13860. case BABYLON.Material.PointFillMode:
  13861. indexToBind = null;
  13862. break;
  13863. case BABYLON.Material.WireFrameFillMode:
  13864. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  13865. break;
  13866. default:
  13867. case BABYLON.Material.TriangleFillMode:
  13868. indexToBind = this._geometry.getIndexBuffer();
  13869. break;
  13870. }
  13871. // VBOs
  13872. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  13873. };
  13874. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  13875. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  13876. return;
  13877. }
  13878. var engine = this.getScene().getEngine();
  13879. switch (fillMode) {
  13880. case BABYLON.Material.PointFillMode:
  13881. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  13882. break;
  13883. case BABYLON.Material.WireFrameFillMode:
  13884. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  13885. break;
  13886. default:
  13887. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  13888. }
  13889. };
  13890. Mesh.prototype.registerBeforeRender = function (func) {
  13891. this._onBeforeRenderCallbacks.push(func);
  13892. };
  13893. Mesh.prototype.unregisterBeforeRender = function (func) {
  13894. var index = this._onBeforeRenderCallbacks.indexOf(func);
  13895. if (index > -1) {
  13896. this._onBeforeRenderCallbacks.splice(index, 1);
  13897. }
  13898. };
  13899. Mesh.prototype.registerAfterRender = function (func) {
  13900. this._onAfterRenderCallbacks.push(func);
  13901. };
  13902. Mesh.prototype.unregisterAfterRender = function (func) {
  13903. var index = this._onAfterRenderCallbacks.indexOf(func);
  13904. if (index > -1) {
  13905. this._onAfterRenderCallbacks.splice(index, 1);
  13906. }
  13907. };
  13908. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  13909. var scene = this.getScene();
  13910. this._batchCache.mustReturn = false;
  13911. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  13912. this._batchCache.visibleInstances[subMeshId] = null;
  13913. if (this._visibleInstances) {
  13914. var currentRenderId = scene.getRenderId();
  13915. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  13916. var selfRenderId = this._renderId;
  13917. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  13918. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  13919. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  13920. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  13921. }
  13922. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  13923. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  13924. this._batchCache.mustReturn = true;
  13925. return this._batchCache;
  13926. }
  13927. if (currentRenderId !== selfRenderId) {
  13928. this._batchCache.renderSelf[subMeshId] = false;
  13929. }
  13930. }
  13931. this._renderIdForInstances[subMeshId] = currentRenderId;
  13932. }
  13933. return this._batchCache;
  13934. };
  13935. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  13936. var visibleInstances = batch.visibleInstances[subMesh._id];
  13937. var matricesCount = visibleInstances.length + 1;
  13938. var bufferSize = matricesCount * 16 * 4;
  13939. while (this._instancesBufferSize < bufferSize) {
  13940. this._instancesBufferSize *= 2;
  13941. }
  13942. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  13943. if (this._worldMatricesInstancesBuffer) {
  13944. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  13945. }
  13946. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  13947. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  13948. }
  13949. var offset = 0;
  13950. var instancesCount = 0;
  13951. var world = this.getWorldMatrix();
  13952. if (batch.renderSelf[subMesh._id]) {
  13953. world.copyToArray(this._worldMatricesInstancesArray, offset);
  13954. offset += 16;
  13955. instancesCount++;
  13956. }
  13957. if (visibleInstances) {
  13958. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  13959. var instance = visibleInstances[instanceIndex];
  13960. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  13961. offset += 16;
  13962. instancesCount++;
  13963. }
  13964. }
  13965. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  13966. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  13967. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  13968. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  13969. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  13970. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  13971. this._draw(subMesh, fillMode, instancesCount);
  13972. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  13973. };
  13974. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  13975. var scene = this.getScene();
  13976. var engine = scene.getEngine();
  13977. if (hardwareInstancedRendering) {
  13978. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  13979. }
  13980. else {
  13981. if (batch.renderSelf[subMesh._id]) {
  13982. // Draw
  13983. if (onBeforeDraw) {
  13984. onBeforeDraw(false, this.getWorldMatrix());
  13985. }
  13986. this._draw(subMesh, fillMode);
  13987. }
  13988. if (batch.visibleInstances[subMesh._id]) {
  13989. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  13990. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  13991. // World
  13992. var world = instance.getWorldMatrix();
  13993. if (onBeforeDraw) {
  13994. onBeforeDraw(true, world);
  13995. }
  13996. // Draw
  13997. this._draw(subMesh, fillMode);
  13998. }
  13999. }
  14000. }
  14001. };
  14002. Mesh.prototype.render = function (subMesh) {
  14003. var scene = this.getScene();
  14004. // Managing instances
  14005. var batch = this._getInstancesRenderList(subMesh._id);
  14006. if (batch.mustReturn) {
  14007. return;
  14008. }
  14009. // Checking geometry state
  14010. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14011. return;
  14012. }
  14013. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14014. this._onBeforeRenderCallbacks[callbackIndex](this);
  14015. }
  14016. var engine = scene.getEngine();
  14017. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14018. // Material
  14019. var effectiveMaterial = subMesh.getMaterial();
  14020. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14021. return;
  14022. }
  14023. // Outline - step 1
  14024. var savedDepthWrite = engine.getDepthWrite();
  14025. if (this.renderOutline) {
  14026. engine.setDepthWrite(false);
  14027. scene.getOutlineRenderer().render(subMesh, batch);
  14028. engine.setDepthWrite(savedDepthWrite);
  14029. }
  14030. effectiveMaterial._preBind();
  14031. var effect = effectiveMaterial.getEffect();
  14032. // Bind
  14033. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14034. this._bind(subMesh, effect, fillMode);
  14035. var world = this.getWorldMatrix();
  14036. effectiveMaterial.bind(world, this);
  14037. // Draw
  14038. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14039. if (isInstance) {
  14040. effectiveMaterial.bindOnlyWorldMatrix(world);
  14041. }
  14042. });
  14043. // Unbind
  14044. effectiveMaterial.unbind();
  14045. // Outline - step 2
  14046. if (this.renderOutline && savedDepthWrite) {
  14047. engine.setDepthWrite(true);
  14048. engine.setColorWrite(false);
  14049. scene.getOutlineRenderer().render(subMesh, batch);
  14050. engine.setColorWrite(true);
  14051. }
  14052. // Overlay
  14053. if (this.renderOverlay) {
  14054. var currentMode = engine.getAlphaMode();
  14055. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14056. scene.getOutlineRenderer().render(subMesh, batch, true);
  14057. engine.setAlphaMode(currentMode);
  14058. }
  14059. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14060. this._onAfterRenderCallbacks[callbackIndex](this);
  14061. }
  14062. };
  14063. Mesh.prototype.getEmittedParticleSystems = function () {
  14064. var results = new Array();
  14065. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14066. var particleSystem = this.getScene().particleSystems[index];
  14067. if (particleSystem.emitter === this) {
  14068. results.push(particleSystem);
  14069. }
  14070. }
  14071. return results;
  14072. };
  14073. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14074. var results = new Array();
  14075. var descendants = this.getDescendants();
  14076. descendants.push(this);
  14077. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14078. var particleSystem = this.getScene().particleSystems[index];
  14079. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14080. results.push(particleSystem);
  14081. }
  14082. }
  14083. return results;
  14084. };
  14085. Mesh.prototype.getChildren = function () {
  14086. var results = [];
  14087. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14088. var mesh = this.getScene().meshes[index];
  14089. if (mesh.parent === this) {
  14090. results.push(mesh);
  14091. }
  14092. }
  14093. return results;
  14094. };
  14095. Mesh.prototype._checkDelayState = function () {
  14096. var _this = this;
  14097. var that = this;
  14098. var scene = this.getScene();
  14099. if (this._geometry) {
  14100. this._geometry.load(scene);
  14101. }
  14102. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14103. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14104. scene._addPendingData(that);
  14105. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14106. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14107. if (data instanceof ArrayBuffer) {
  14108. _this._delayLoadingFunction(data, _this);
  14109. }
  14110. else {
  14111. _this._delayLoadingFunction(JSON.parse(data), _this);
  14112. }
  14113. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14114. scene._removePendingData(_this);
  14115. }, function () {
  14116. }, scene.database, getBinaryData);
  14117. }
  14118. };
  14119. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14120. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14121. return false;
  14122. }
  14123. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14124. return false;
  14125. }
  14126. this._checkDelayState();
  14127. return true;
  14128. };
  14129. Mesh.prototype.setMaterialByID = function (id) {
  14130. var materials = this.getScene().materials;
  14131. for (var index = 0; index < materials.length; index++) {
  14132. if (materials[index].id === id) {
  14133. this.material = materials[index];
  14134. return;
  14135. }
  14136. }
  14137. // Multi
  14138. var multiMaterials = this.getScene().multiMaterials;
  14139. for (index = 0; index < multiMaterials.length; index++) {
  14140. if (multiMaterials[index].id === id) {
  14141. this.material = multiMaterials[index];
  14142. return;
  14143. }
  14144. }
  14145. };
  14146. Mesh.prototype.getAnimatables = function () {
  14147. var results = [];
  14148. if (this.material) {
  14149. results.push(this.material);
  14150. }
  14151. if (this.skeleton) {
  14152. results.push(this.skeleton);
  14153. }
  14154. return results;
  14155. };
  14156. // Geometry
  14157. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14158. // Position
  14159. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14160. return;
  14161. }
  14162. this._resetPointsArrayCache();
  14163. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14164. var temp = [];
  14165. for (var index = 0; index < data.length; index += 3) {
  14166. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14167. }
  14168. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14169. // Normals
  14170. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14171. return;
  14172. }
  14173. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14174. temp = [];
  14175. for (index = 0; index < data.length; index += 3) {
  14176. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14177. }
  14178. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14179. };
  14180. // Cache
  14181. Mesh.prototype._resetPointsArrayCache = function () {
  14182. this._positions = null;
  14183. };
  14184. Mesh.prototype._generatePointsArray = function () {
  14185. if (this._positions)
  14186. return true;
  14187. this._positions = [];
  14188. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14189. if (!data) {
  14190. return false;
  14191. }
  14192. for (var index = 0; index < data.length; index += 3) {
  14193. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14194. }
  14195. return true;
  14196. };
  14197. // Clone
  14198. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14199. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14200. };
  14201. // Dispose
  14202. Mesh.prototype.dispose = function (doNotRecurse) {
  14203. if (this._geometry) {
  14204. this._geometry.releaseForMesh(this, true);
  14205. }
  14206. // Instances
  14207. if (this._worldMatricesInstancesBuffer) {
  14208. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14209. this._worldMatricesInstancesBuffer = null;
  14210. }
  14211. while (this.instances.length) {
  14212. this.instances[0].dispose();
  14213. }
  14214. _super.prototype.dispose.call(this, doNotRecurse);
  14215. };
  14216. // Geometric tools
  14217. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14218. var _this = this;
  14219. var scene = this.getScene();
  14220. var onload = function (img) {
  14221. // Getting height map data
  14222. var canvas = document.createElement("canvas");
  14223. var context = canvas.getContext("2d");
  14224. var heightMapWidth = img.width;
  14225. var heightMapHeight = img.height;
  14226. canvas.width = heightMapWidth;
  14227. canvas.height = heightMapHeight;
  14228. context.drawImage(img, 0, 0);
  14229. // Create VertexData from map data
  14230. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14231. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14232. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14233. //execute success callback, if set
  14234. if (onSuccess) {
  14235. onSuccess(_this);
  14236. }
  14237. };
  14238. BABYLON.Tools.LoadImage(url, onload, function () {
  14239. }, scene.database);
  14240. };
  14241. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14242. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14243. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14244. return;
  14245. }
  14246. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14247. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14248. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14249. var position = BABYLON.Vector3.Zero();
  14250. var normal = BABYLON.Vector3.Zero();
  14251. var uv = BABYLON.Vector2.Zero();
  14252. for (var index = 0; index < positions.length; index += 3) {
  14253. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14254. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14255. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14256. // Compute height
  14257. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14258. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14259. var pos = (u + v * heightMapWidth) * 4;
  14260. var r = buffer[pos] / 255.0;
  14261. var g = buffer[pos + 1] / 255.0;
  14262. var b = buffer[pos + 2] / 255.0;
  14263. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14264. normal.normalize();
  14265. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14266. position = position.add(normal);
  14267. position.toArray(positions, index);
  14268. }
  14269. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14270. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14271. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14272. };
  14273. Mesh.prototype.convertToFlatShadedMesh = function () {
  14274. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14275. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14276. var kinds = this.getVerticesDataKinds();
  14277. var vbs = [];
  14278. var data = [];
  14279. var newdata = [];
  14280. var updatableNormals = false;
  14281. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14282. var kind = kinds[kindIndex];
  14283. var vertexBuffer = this.getVertexBuffer(kind);
  14284. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14285. updatableNormals = vertexBuffer.isUpdatable();
  14286. kinds.splice(kindIndex, 1);
  14287. kindIndex--;
  14288. continue;
  14289. }
  14290. vbs[kind] = vertexBuffer;
  14291. data[kind] = vbs[kind].getData();
  14292. newdata[kind] = [];
  14293. }
  14294. // Save previous submeshes
  14295. var previousSubmeshes = this.subMeshes.slice(0);
  14296. var indices = this.getIndices();
  14297. var totalIndices = this.getTotalIndices();
  14298. for (var index = 0; index < totalIndices; index++) {
  14299. var vertexIndex = indices[index];
  14300. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14301. kind = kinds[kindIndex];
  14302. var stride = vbs[kind].getStrideSize();
  14303. for (var offset = 0; offset < stride; offset++) {
  14304. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14305. }
  14306. }
  14307. }
  14308. // Updating faces & normal
  14309. var normals = [];
  14310. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14311. for (index = 0; index < totalIndices; index += 3) {
  14312. indices[index] = index;
  14313. indices[index + 1] = index + 1;
  14314. indices[index + 2] = index + 2;
  14315. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14316. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14317. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14318. var p1p2 = p1.subtract(p2);
  14319. var p3p2 = p3.subtract(p2);
  14320. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14321. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14322. normals.push(normal.x);
  14323. normals.push(normal.y);
  14324. normals.push(normal.z);
  14325. }
  14326. }
  14327. this.setIndices(indices);
  14328. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  14329. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14330. kind = kinds[kindIndex];
  14331. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  14332. }
  14333. // Updating submeshes
  14334. this.releaseSubMeshes();
  14335. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14336. var previousOne = previousSubmeshes[submeshIndex];
  14337. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14338. }
  14339. this.synchronizeInstances();
  14340. };
  14341. // Instances
  14342. Mesh.prototype.createInstance = function (name) {
  14343. return new BABYLON.InstancedMesh(name, this);
  14344. };
  14345. Mesh.prototype.synchronizeInstances = function () {
  14346. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14347. var instance = this.instances[instanceIndex];
  14348. instance._syncSubMeshes();
  14349. }
  14350. };
  14351. /**
  14352. * Simplify the mesh according to the given array of settings.
  14353. * Function will return immediately and will simplify async.
  14354. * @param settings a collection of simplification settings.
  14355. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14356. * @param type the type of simplification to run.
  14357. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14358. */
  14359. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14360. if (parallelProcessing === void 0) { parallelProcessing = true; }
  14361. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  14362. this.getScene().simplificationQueue.addTask({
  14363. settings: settings,
  14364. parallelProcessing: parallelProcessing,
  14365. mesh: this,
  14366. simplificationType: simplificationType,
  14367. successCallback: successCallback
  14368. });
  14369. };
  14370. /**
  14371. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  14372. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  14373. * This should be used together with the simplification to avoid disappearing triangles.
  14374. * @param successCallback an optional success callback to be called after the optimization finished.
  14375. */
  14376. Mesh.prototype.optimizeIndices = function (successCallback) {
  14377. var _this = this;
  14378. var indices = this.getIndices();
  14379. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14380. var vectorPositions = [];
  14381. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  14382. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  14383. }
  14384. var dupes = [];
  14385. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  14386. var realPos = vectorPositions.length - 1 - iteration;
  14387. var testedPosition = vectorPositions[realPos];
  14388. for (var j = 0; j < realPos; ++j) {
  14389. var againstPosition = vectorPositions[j];
  14390. if (testedPosition.equals(againstPosition)) {
  14391. dupes[realPos] = j;
  14392. break;
  14393. }
  14394. }
  14395. }, function () {
  14396. for (var i = 0; i < indices.length; ++i) {
  14397. indices[i] = dupes[indices[i]] || indices[i];
  14398. }
  14399. //indices are now reordered
  14400. var originalSubMeshes = _this.subMeshes.slice(0);
  14401. _this.setIndices(indices);
  14402. _this.subMeshes = originalSubMeshes;
  14403. if (successCallback) {
  14404. successCallback(_this);
  14405. }
  14406. });
  14407. };
  14408. // Statics
  14409. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  14410. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14411. if (ribbonInstance === void 0) { ribbonInstance = null; }
  14412. if (ribbonInstance) {
  14413. // positionFunction : ribbon case
  14414. // only pathArray and sideOrientation parameters are taken into account for positions update
  14415. var positionsOfRibbon = function (pathArray, sideOrientation) {
  14416. var positionFunction = function (positions) {
  14417. var minlg = pathArray[0].length;
  14418. var i = 0;
  14419. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  14420. for (var si = 1; si <= ns; si++) {
  14421. for (var p = 0; p < pathArray.length; p++) {
  14422. var path = pathArray[p];
  14423. var l = path.length;
  14424. minlg = (minlg < l) ? minlg : l;
  14425. var j = 0;
  14426. while (j < minlg) {
  14427. positions[i] = path[j].x;
  14428. positions[i + 1] = path[j].y;
  14429. positions[i + 2] = path[j].z;
  14430. j++;
  14431. i += 3;
  14432. }
  14433. }
  14434. }
  14435. };
  14436. return positionFunction;
  14437. };
  14438. var sideOrientation = ribbonInstance.sideOrientation;
  14439. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  14440. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  14441. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  14442. return ribbonInstance;
  14443. }
  14444. else {
  14445. var ribbon = new Mesh(name, scene);
  14446. ribbon.sideOrientation = sideOrientation;
  14447. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  14448. vertexData.applyToMesh(ribbon, updatable);
  14449. return ribbon;
  14450. }
  14451. };
  14452. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  14453. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14454. var disc = new Mesh(name, scene);
  14455. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  14456. vertexData.applyToMesh(disc, updatable);
  14457. return disc;
  14458. };
  14459. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  14460. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14461. var box = new Mesh(name, scene);
  14462. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  14463. vertexData.applyToMesh(box, updatable);
  14464. return box;
  14465. };
  14466. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  14467. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14468. var sphere = new Mesh(name, scene);
  14469. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  14470. vertexData.applyToMesh(sphere, updatable);
  14471. return sphere;
  14472. };
  14473. // Cylinder and cone (Code inspired by SharpDX.org)
  14474. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  14475. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14476. // subdivisions is a new parameter, we need to support old signature
  14477. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  14478. if (scene !== undefined) {
  14479. updatable = scene;
  14480. }
  14481. scene = subdivisions;
  14482. subdivisions = 1;
  14483. }
  14484. var cylinder = new Mesh(name, scene);
  14485. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  14486. vertexData.applyToMesh(cylinder, updatable);
  14487. return cylinder;
  14488. };
  14489. // Torus (Code from SharpDX.org)
  14490. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  14491. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14492. var torus = new Mesh(name, scene);
  14493. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  14494. vertexData.applyToMesh(torus, updatable);
  14495. return torus;
  14496. };
  14497. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  14498. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14499. var torusKnot = new Mesh(name, scene);
  14500. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  14501. vertexData.applyToMesh(torusKnot, updatable);
  14502. return torusKnot;
  14503. };
  14504. // Lines
  14505. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  14506. if (linesInstance === void 0) { linesInstance = null; }
  14507. if (linesInstance) {
  14508. var positionsOfLines = function (points) {
  14509. var positionFunction = function (positions) {
  14510. var i = 0;
  14511. for (var p = 0; p < points.length; p++) {
  14512. positions[i] = points[p].x;
  14513. positions[i + 1] = points[p].y;
  14514. positions[i + 2] = points[p].z;
  14515. i += 3;
  14516. }
  14517. };
  14518. return positionFunction;
  14519. };
  14520. var positionFunction = positionsOfLines(points);
  14521. linesInstance.updateMeshPositions(positionFunction, false);
  14522. return linesInstance;
  14523. }
  14524. // lines creation
  14525. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  14526. var vertexData = BABYLON.VertexData.CreateLines(points);
  14527. vertexData.applyToMesh(lines, updatable);
  14528. return lines;
  14529. };
  14530. // Extrusion
  14531. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  14532. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14533. if (extrudedInstance === void 0) { extrudedInstance = null; }
  14534. scale = scale || 1;
  14535. rotation = rotation || 0;
  14536. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  14537. return extruded;
  14538. };
  14539. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  14540. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14541. if (extrudedInstance === void 0) { extrudedInstance = null; }
  14542. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  14543. return extrudedCustom;
  14544. };
  14545. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  14546. // extrusion geometry
  14547. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  14548. var tangents = path3D.getTangents();
  14549. var normals = path3D.getNormals();
  14550. var binormals = path3D.getBinormals();
  14551. var distances = path3D.getDistances();
  14552. var angle = 0;
  14553. var returnScale = function (i, distance) {
  14554. return scale;
  14555. };
  14556. var returnRotation = function (i, distance) {
  14557. return rotation;
  14558. };
  14559. var rotate = custom ? rotateFunction : returnRotation;
  14560. var scl = custom ? scaleFunction : returnScale;
  14561. var index = 0;
  14562. for (var i = 0; i < curve.length; i++) {
  14563. var shapePath = new Array();
  14564. var angleStep = rotate(i, distances[i]);
  14565. var scaleRatio = scl(i, distances[i]);
  14566. for (var p = 0; p < shape.length; p++) {
  14567. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  14568. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  14569. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  14570. shapePath.push(rotated);
  14571. }
  14572. shapePaths[index] = shapePath;
  14573. angle += angleStep;
  14574. index++;
  14575. }
  14576. // cap
  14577. var capPath = function (shapePath) {
  14578. var pointCap = Array();
  14579. var barycenter = BABYLON.Vector3.Zero();
  14580. var i;
  14581. for (i = 0; i < shapePath.length; i++) {
  14582. barycenter.addInPlace(shapePath[i]);
  14583. }
  14584. barycenter.scaleInPlace(1 / shapePath.length);
  14585. for (i = 0; i < shapePath.length; i++) {
  14586. pointCap.push(barycenter);
  14587. }
  14588. return pointCap;
  14589. };
  14590. switch (cap) {
  14591. case BABYLON.Mesh.NO_CAP:
  14592. break;
  14593. case BABYLON.Mesh.CAP_START:
  14594. shapePaths.unshift(capPath(shapePaths[0]));
  14595. break;
  14596. case BABYLON.Mesh.CAP_END:
  14597. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  14598. break;
  14599. case BABYLON.Mesh.CAP_ALL:
  14600. shapePaths.unshift(capPath(shapePaths[0]));
  14601. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  14602. break;
  14603. default:
  14604. break;
  14605. }
  14606. return shapePaths;
  14607. };
  14608. if (instance) {
  14609. var path3D = (instance.path3D).update(curve);
  14610. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  14611. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  14612. return instance;
  14613. }
  14614. // extruded shape creation
  14615. var path3D = new BABYLON.Path3D(curve);
  14616. var newShapePaths = new Array();
  14617. cap = (cap < 0 || cap > 3) ? 0 : cap;
  14618. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  14619. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  14620. extrudedGeneric.pathArray = pathArray;
  14621. extrudedGeneric.path3D = path3D;
  14622. extrudedGeneric.cap = cap;
  14623. return extrudedGeneric;
  14624. };
  14625. // Plane & ground
  14626. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  14627. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14628. var plane = new Mesh(name, scene);
  14629. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  14630. vertexData.applyToMesh(plane, updatable);
  14631. return plane;
  14632. };
  14633. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  14634. var ground = new BABYLON.GroundMesh(name, scene);
  14635. ground._setReady(false);
  14636. ground._subdivisions = subdivisions;
  14637. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  14638. vertexData.applyToMesh(ground, updatable);
  14639. ground._setReady(true);
  14640. return ground;
  14641. };
  14642. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  14643. var tiledGround = new Mesh(name, scene);
  14644. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  14645. vertexData.applyToMesh(tiledGround, updatable);
  14646. return tiledGround;
  14647. };
  14648. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  14649. var ground = new BABYLON.GroundMesh(name, scene);
  14650. ground._subdivisions = subdivisions;
  14651. ground._setReady(false);
  14652. var onload = function (img) {
  14653. // Getting height map data
  14654. var canvas = document.createElement("canvas");
  14655. var context = canvas.getContext("2d");
  14656. var heightMapWidth = img.width;
  14657. var heightMapHeight = img.height;
  14658. canvas.width = heightMapWidth;
  14659. canvas.height = heightMapHeight;
  14660. context.drawImage(img, 0, 0);
  14661. // Create VertexData from map data
  14662. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14663. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14664. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  14665. vertexData.applyToMesh(ground, updatable);
  14666. ground._setReady(true);
  14667. //execute ready callback, if set
  14668. if (onReady) {
  14669. onReady(ground);
  14670. }
  14671. };
  14672. BABYLON.Tools.LoadImage(url, onload, function () {
  14673. }, scene.database);
  14674. return ground;
  14675. };
  14676. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  14677. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  14678. if (tubeInstance === void 0) { tubeInstance = null; }
  14679. // tube geometry
  14680. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  14681. var tangents = path3D.getTangents();
  14682. var normals = path3D.getNormals();
  14683. var distances = path3D.getDistances();
  14684. var pi2 = Math.PI * 2;
  14685. var step = pi2 / tessellation;
  14686. var returnRadius = function (i, distance) { return radius; };
  14687. var radiusFunctionFinal = radiusFunction || returnRadius;
  14688. var circlePath;
  14689. var rad;
  14690. var normal;
  14691. var rotated;
  14692. var rotationMatrix;
  14693. var index = 0;
  14694. for (var i = 0; i < path.length; i++) {
  14695. rad = radiusFunctionFinal(i, distances[i]); // current radius
  14696. circlePath = Array(); // current circle array
  14697. normal = normals[i]; // current normal
  14698. for (var t = 0; t < tessellation; t++) {
  14699. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  14700. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  14701. circlePath.push(rotated);
  14702. }
  14703. circlePath.push(circlePath[0]);
  14704. circlePaths[index] = circlePath;
  14705. index++;
  14706. }
  14707. // cap
  14708. var capPath = function (nbPoints, pathIndex) {
  14709. var pointCap = Array();
  14710. for (var i = 0; i < nbPoints; i++) {
  14711. pointCap.push(path[pathIndex]);
  14712. }
  14713. return pointCap;
  14714. };
  14715. switch (cap) {
  14716. case BABYLON.Mesh.NO_CAP:
  14717. break;
  14718. case BABYLON.Mesh.CAP_START:
  14719. circlePaths.unshift(capPath(tessellation + 1, 0));
  14720. break;
  14721. case BABYLON.Mesh.CAP_END:
  14722. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  14723. break;
  14724. case BABYLON.Mesh.CAP_ALL:
  14725. circlePaths.unshift(capPath(tessellation + 1, 0));
  14726. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  14727. break;
  14728. default:
  14729. break;
  14730. }
  14731. return circlePaths;
  14732. };
  14733. if (tubeInstance) {
  14734. var path3D = (tubeInstance.path3D).update(path);
  14735. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  14736. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  14737. return tubeInstance;
  14738. }
  14739. // tube creation
  14740. var path3D = new BABYLON.Path3D(path);
  14741. var newPathArray = new Array();
  14742. cap = (cap < 0 || cap > 3) ? 0 : cap;
  14743. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  14744. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  14745. tube.pathArray = pathArray;
  14746. tube.path3D = path3D;
  14747. tube.tessellation = tessellation;
  14748. tube.cap = cap;
  14749. return tube;
  14750. };
  14751. // Decals
  14752. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  14753. if (angle === void 0) { angle = 0; }
  14754. var indices = sourceMesh.getIndices();
  14755. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14756. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14757. // Getting correct rotation
  14758. if (!normal) {
  14759. var target = new BABYLON.Vector3(0, 0, 1);
  14760. var camera = sourceMesh.getScene().activeCamera;
  14761. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  14762. normal = camera.globalPosition.subtract(cameraWorldTarget);
  14763. }
  14764. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  14765. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  14766. var pitch = Math.atan2(normal.y, len);
  14767. // Matrix
  14768. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  14769. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  14770. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  14771. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  14772. var vertexData = new BABYLON.VertexData();
  14773. vertexData.indices = [];
  14774. vertexData.positions = [];
  14775. vertexData.normals = [];
  14776. vertexData.uvs = [];
  14777. var currentVertexDataIndex = 0;
  14778. var extractDecalVector3 = function (indexId) {
  14779. var vertexId = indices[indexId];
  14780. var result = new BABYLON.PositionNormalVertex();
  14781. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  14782. // Send vector to decal local world
  14783. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  14784. // Get normal
  14785. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  14786. return result;
  14787. };
  14788. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  14789. var clip = function (vertices, axis) {
  14790. if (vertices.length === 0) {
  14791. return vertices;
  14792. }
  14793. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  14794. var clipVertices = function (v0, v1) {
  14795. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  14796. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  14797. };
  14798. var result = new Array();
  14799. for (var index = 0; index < vertices.length; index += 3) {
  14800. var v1Out;
  14801. var v2Out;
  14802. var v3Out;
  14803. var total = 0;
  14804. var nV1, nV2, nV3, nV4;
  14805. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  14806. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  14807. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  14808. v1Out = d1 > 0;
  14809. v2Out = d2 > 0;
  14810. v3Out = d3 > 0;
  14811. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  14812. switch (total) {
  14813. case 0:
  14814. result.push(vertices[index]);
  14815. result.push(vertices[index + 1]);
  14816. result.push(vertices[index + 2]);
  14817. break;
  14818. case 1:
  14819. if (v1Out) {
  14820. nV1 = vertices[index + 1];
  14821. nV2 = vertices[index + 2];
  14822. nV3 = clipVertices(vertices[index], nV1);
  14823. nV4 = clipVertices(vertices[index], nV2);
  14824. }
  14825. if (v2Out) {
  14826. nV1 = vertices[index];
  14827. nV2 = vertices[index + 2];
  14828. nV3 = clipVertices(vertices[index + 1], nV1);
  14829. nV4 = clipVertices(vertices[index + 1], nV2);
  14830. result.push(nV3);
  14831. result.push(nV2.clone());
  14832. result.push(nV1.clone());
  14833. result.push(nV2.clone());
  14834. result.push(nV3.clone());
  14835. result.push(nV4);
  14836. break;
  14837. }
  14838. if (v3Out) {
  14839. nV1 = vertices[index];
  14840. nV2 = vertices[index + 1];
  14841. nV3 = clipVertices(vertices[index + 2], nV1);
  14842. nV4 = clipVertices(vertices[index + 2], nV2);
  14843. }
  14844. result.push(nV1.clone());
  14845. result.push(nV2.clone());
  14846. result.push(nV3);
  14847. result.push(nV4);
  14848. result.push(nV3.clone());
  14849. result.push(nV2.clone());
  14850. break;
  14851. case 2:
  14852. if (!v1Out) {
  14853. nV1 = vertices[index].clone();
  14854. nV2 = clipVertices(nV1, vertices[index + 1]);
  14855. nV3 = clipVertices(nV1, vertices[index + 2]);
  14856. result.push(nV1);
  14857. result.push(nV2);
  14858. result.push(nV3);
  14859. }
  14860. if (!v2Out) {
  14861. nV1 = vertices[index + 1].clone();
  14862. nV2 = clipVertices(nV1, vertices[index + 2]);
  14863. nV3 = clipVertices(nV1, vertices[index]);
  14864. result.push(nV1);
  14865. result.push(nV2);
  14866. result.push(nV3);
  14867. }
  14868. if (!v3Out) {
  14869. nV1 = vertices[index + 2].clone();
  14870. nV2 = clipVertices(nV1, vertices[index]);
  14871. nV3 = clipVertices(nV1, vertices[index + 1]);
  14872. result.push(nV1);
  14873. result.push(nV2);
  14874. result.push(nV3);
  14875. }
  14876. break;
  14877. case 3:
  14878. break;
  14879. }
  14880. }
  14881. return result;
  14882. };
  14883. for (var index = 0; index < indices.length; index += 3) {
  14884. var faceVertices = new Array();
  14885. faceVertices.push(extractDecalVector3(index));
  14886. faceVertices.push(extractDecalVector3(index + 1));
  14887. faceVertices.push(extractDecalVector3(index + 2));
  14888. // Clip
  14889. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  14890. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  14891. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  14892. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  14893. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  14894. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  14895. if (faceVertices.length === 0) {
  14896. continue;
  14897. }
  14898. // Add UVs and get back to world
  14899. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  14900. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  14901. var vertex = faceVertices[vIndex];
  14902. vertexData.indices.push(currentVertexDataIndex);
  14903. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  14904. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  14905. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  14906. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  14907. currentVertexDataIndex++;
  14908. }
  14909. }
  14910. // Return mesh
  14911. var decal = new Mesh(name, sourceMesh.getScene());
  14912. vertexData.applyToMesh(decal);
  14913. decal.position = position.clone();
  14914. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  14915. return decal;
  14916. };
  14917. // Tools
  14918. Mesh.MinMax = function (meshes) {
  14919. var minVector = null;
  14920. var maxVector = null;
  14921. for (var i in meshes) {
  14922. var mesh = meshes[i];
  14923. var boundingBox = mesh.getBoundingInfo().boundingBox;
  14924. if (!minVector) {
  14925. minVector = boundingBox.minimumWorld;
  14926. maxVector = boundingBox.maximumWorld;
  14927. continue;
  14928. }
  14929. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  14930. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  14931. }
  14932. return {
  14933. min: minVector,
  14934. max: maxVector
  14935. };
  14936. };
  14937. Mesh.Center = function (meshesOrMinMaxVector) {
  14938. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  14939. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  14940. };
  14941. /**
  14942. * Merge the array of meshes into a single mesh for performance reasons.
  14943. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  14944. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  14945. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  14946. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  14947. */
  14948. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  14949. if (disposeSource === void 0) { disposeSource = true; }
  14950. if (!allow32BitsIndices) {
  14951. var totalVertices = 0;
  14952. for (var index = 0; index < meshes.length; index++) {
  14953. if (meshes[index]) {
  14954. totalVertices += meshes[index].getTotalVertices();
  14955. if (totalVertices > 65536) {
  14956. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  14957. return null;
  14958. }
  14959. }
  14960. }
  14961. }
  14962. // Merge
  14963. var vertexData;
  14964. var otherVertexData;
  14965. var source;
  14966. for (index = 0; index < meshes.length; index++) {
  14967. if (meshes[index]) {
  14968. meshes[index].computeWorldMatrix(true);
  14969. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  14970. otherVertexData.transform(meshes[index].getWorldMatrix());
  14971. if (vertexData) {
  14972. vertexData.merge(otherVertexData);
  14973. }
  14974. else {
  14975. vertexData = otherVertexData;
  14976. source = meshes[index];
  14977. }
  14978. }
  14979. }
  14980. if (!meshSubclass) {
  14981. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  14982. }
  14983. vertexData.applyToMesh(meshSubclass);
  14984. // Setting properties
  14985. meshSubclass.material = source.material;
  14986. meshSubclass.checkCollisions = source.checkCollisions;
  14987. // Cleaning
  14988. if (disposeSource) {
  14989. for (index = 0; index < meshes.length; index++) {
  14990. if (meshes[index]) {
  14991. meshes[index].dispose();
  14992. }
  14993. }
  14994. }
  14995. return meshSubclass;
  14996. };
  14997. // Consts
  14998. Mesh._FRONTSIDE = 0;
  14999. Mesh._BACKSIDE = 1;
  15000. Mesh._DOUBLESIDE = 2;
  15001. Mesh._DEFAULTSIDE = 0;
  15002. Mesh._NO_CAP = 0;
  15003. Mesh._CAP_START = 1;
  15004. Mesh._CAP_END = 2;
  15005. Mesh._CAP_ALL = 3;
  15006. return Mesh;
  15007. })(BABYLON.AbstractMesh);
  15008. BABYLON.Mesh = Mesh;
  15009. })(BABYLON || (BABYLON = {}));
  15010. //# sourceMappingURL=babylon.mesh.js.map
  15011. var BABYLON;
  15012. (function (BABYLON) {
  15013. var SubMesh = (function () {
  15014. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15015. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15016. this.materialIndex = materialIndex;
  15017. this.verticesStart = verticesStart;
  15018. this.verticesCount = verticesCount;
  15019. this.indexStart = indexStart;
  15020. this.indexCount = indexCount;
  15021. this._renderId = 0;
  15022. this._mesh = mesh;
  15023. this._renderingMesh = renderingMesh || mesh;
  15024. mesh.subMeshes.push(this);
  15025. this._trianglePlanes = [];
  15026. this._id = mesh.subMeshes.length - 1;
  15027. if (createBoundingBox) {
  15028. this.refreshBoundingInfo();
  15029. mesh.computeWorldMatrix(true);
  15030. }
  15031. }
  15032. SubMesh.prototype.getBoundingInfo = function () {
  15033. return this._boundingInfo;
  15034. };
  15035. SubMesh.prototype.getMesh = function () {
  15036. return this._mesh;
  15037. };
  15038. SubMesh.prototype.getRenderingMesh = function () {
  15039. return this._renderingMesh;
  15040. };
  15041. SubMesh.prototype.getMaterial = function () {
  15042. var rootMaterial = this._renderingMesh.material;
  15043. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15044. var multiMaterial = rootMaterial;
  15045. return multiMaterial.getSubMaterial(this.materialIndex);
  15046. }
  15047. if (!rootMaterial) {
  15048. return this._mesh.getScene().defaultMaterial;
  15049. }
  15050. return rootMaterial;
  15051. };
  15052. // Methods
  15053. SubMesh.prototype.refreshBoundingInfo = function () {
  15054. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15055. if (!data) {
  15056. this._boundingInfo = this._mesh._boundingInfo;
  15057. return;
  15058. }
  15059. var indices = this._renderingMesh.getIndices();
  15060. var extend;
  15061. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15062. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  15063. }
  15064. else {
  15065. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15066. }
  15067. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15068. };
  15069. SubMesh.prototype._checkCollision = function (collider) {
  15070. return this._boundingInfo._checkCollision(collider);
  15071. };
  15072. SubMesh.prototype.updateBoundingInfo = function (world) {
  15073. if (!this._boundingInfo) {
  15074. this.refreshBoundingInfo();
  15075. }
  15076. this._boundingInfo._update(world);
  15077. };
  15078. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15079. return this._boundingInfo.isInFrustum(frustumPlanes);
  15080. };
  15081. SubMesh.prototype.render = function () {
  15082. this._renderingMesh.render(this);
  15083. };
  15084. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15085. if (!this._linesIndexBuffer) {
  15086. var linesIndices = [];
  15087. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15088. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15089. }
  15090. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15091. this.linesIndexCount = linesIndices.length;
  15092. }
  15093. return this._linesIndexBuffer;
  15094. };
  15095. SubMesh.prototype.canIntersects = function (ray) {
  15096. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15097. };
  15098. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15099. var intersectInfo = null;
  15100. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15101. var p0 = positions[indices[index]];
  15102. var p1 = positions[indices[index + 1]];
  15103. var p2 = positions[indices[index + 2]];
  15104. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15105. if (currentIntersectInfo) {
  15106. if (currentIntersectInfo.distance < 0) {
  15107. continue;
  15108. }
  15109. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15110. intersectInfo = currentIntersectInfo;
  15111. intersectInfo.faceId = index / 3;
  15112. if (fastCheck) {
  15113. break;
  15114. }
  15115. }
  15116. }
  15117. }
  15118. return intersectInfo;
  15119. };
  15120. // Clone
  15121. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15122. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15123. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15124. return result;
  15125. };
  15126. // Dispose
  15127. SubMesh.prototype.dispose = function () {
  15128. if (this._linesIndexBuffer) {
  15129. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15130. this._linesIndexBuffer = null;
  15131. }
  15132. // Remove from mesh
  15133. var index = this._mesh.subMeshes.indexOf(this);
  15134. this._mesh.subMeshes.splice(index, 1);
  15135. };
  15136. // Statics
  15137. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15138. var minVertexIndex = Number.MAX_VALUE;
  15139. var maxVertexIndex = -Number.MAX_VALUE;
  15140. renderingMesh = renderingMesh || mesh;
  15141. var indices = renderingMesh.getIndices();
  15142. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15143. var vertexIndex = indices[index];
  15144. if (vertexIndex < minVertexIndex)
  15145. minVertexIndex = vertexIndex;
  15146. if (vertexIndex > maxVertexIndex)
  15147. maxVertexIndex = vertexIndex;
  15148. }
  15149. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15150. };
  15151. return SubMesh;
  15152. })();
  15153. BABYLON.SubMesh = SubMesh;
  15154. })(BABYLON || (BABYLON = {}));
  15155. //# sourceMappingURL=babylon.subMesh.js.map
  15156. var BABYLON;
  15157. (function (BABYLON) {
  15158. var BaseTexture = (function () {
  15159. function BaseTexture(scene) {
  15160. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15161. this.hasAlpha = false;
  15162. this.getAlphaFromRGB = false;
  15163. this.level = 1;
  15164. this.isCube = false;
  15165. this.isRenderTarget = false;
  15166. this.animations = new Array();
  15167. this.coordinatesIndex = 0;
  15168. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  15169. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15170. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15171. this.anisotropicFilteringLevel = 4;
  15172. this._scene = scene;
  15173. this._scene.textures.push(this);
  15174. }
  15175. BaseTexture.prototype.getScene = function () {
  15176. return this._scene;
  15177. };
  15178. BaseTexture.prototype.getTextureMatrix = function () {
  15179. return null;
  15180. };
  15181. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  15182. return null;
  15183. };
  15184. BaseTexture.prototype.getInternalTexture = function () {
  15185. return this._texture;
  15186. };
  15187. BaseTexture.prototype.isReady = function () {
  15188. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15189. return true;
  15190. }
  15191. if (this._texture) {
  15192. return this._texture.isReady;
  15193. }
  15194. return false;
  15195. };
  15196. BaseTexture.prototype.getSize = function () {
  15197. if (this._texture._width) {
  15198. return { width: this._texture._width, height: this._texture._height };
  15199. }
  15200. if (this._texture._size) {
  15201. return { width: this._texture._size, height: this._texture._size };
  15202. }
  15203. return { width: 0, height: 0 };
  15204. };
  15205. BaseTexture.prototype.getBaseSize = function () {
  15206. if (!this.isReady())
  15207. return { width: 0, height: 0 };
  15208. if (this._texture._size) {
  15209. return { width: this._texture._size, height: this._texture._size };
  15210. }
  15211. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  15212. };
  15213. BaseTexture.prototype.scale = function (ratio) {
  15214. };
  15215. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  15216. get: function () {
  15217. return false;
  15218. },
  15219. enumerable: true,
  15220. configurable: true
  15221. });
  15222. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  15223. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15224. for (var index = 0; index < texturesCache.length; index++) {
  15225. var texturesCacheEntry = texturesCache[index];
  15226. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15227. texturesCache.splice(index, 1);
  15228. return;
  15229. }
  15230. }
  15231. };
  15232. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  15233. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15234. for (var index = 0; index < texturesCache.length; index++) {
  15235. var texturesCacheEntry = texturesCache[index];
  15236. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15237. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  15238. texturesCacheEntry.references++;
  15239. return texturesCacheEntry;
  15240. }
  15241. }
  15242. }
  15243. return null;
  15244. };
  15245. BaseTexture.prototype.delayLoad = function () {
  15246. };
  15247. BaseTexture.prototype.releaseInternalTexture = function () {
  15248. if (!this._texture) {
  15249. return;
  15250. }
  15251. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15252. this._texture.references--;
  15253. // Final reference ?
  15254. if (this._texture.references === 0) {
  15255. var index = texturesCache.indexOf(this._texture);
  15256. texturesCache.splice(index, 1);
  15257. this._scene.getEngine()._releaseTexture(this._texture);
  15258. delete this._texture;
  15259. }
  15260. };
  15261. BaseTexture.prototype.clone = function () {
  15262. return null;
  15263. };
  15264. BaseTexture.prototype.dispose = function () {
  15265. // Remove from scene
  15266. var index = this._scene.textures.indexOf(this);
  15267. if (index >= 0) {
  15268. this._scene.textures.splice(index, 1);
  15269. }
  15270. if (this._texture === undefined) {
  15271. return;
  15272. }
  15273. this.releaseInternalTexture();
  15274. // Callback
  15275. if (this.onDispose) {
  15276. this.onDispose();
  15277. }
  15278. };
  15279. return BaseTexture;
  15280. })();
  15281. BABYLON.BaseTexture = BaseTexture;
  15282. })(BABYLON || (BABYLON = {}));
  15283. //# sourceMappingURL=babylon.baseTexture.js.map
  15284. var __extends = this.__extends || function (d, b) {
  15285. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15286. function __() { this.constructor = d; }
  15287. __.prototype = b.prototype;
  15288. d.prototype = new __();
  15289. };
  15290. var BABYLON;
  15291. (function (BABYLON) {
  15292. var Texture = (function (_super) {
  15293. __extends(Texture, _super);
  15294. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  15295. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  15296. if (onLoad === void 0) { onLoad = null; }
  15297. if (onError === void 0) { onError = null; }
  15298. if (buffer === void 0) { buffer = null; }
  15299. if (deleteBuffer === void 0) { deleteBuffer = false; }
  15300. _super.call(this, scene);
  15301. this.uOffset = 0;
  15302. this.vOffset = 0;
  15303. this.uScale = 1.0;
  15304. this.vScale = 1.0;
  15305. this.uAng = 0;
  15306. this.vAng = 0;
  15307. this.wAng = 0;
  15308. this.name = url;
  15309. this.url = url;
  15310. this._noMipmap = noMipmap;
  15311. this._invertY = invertY;
  15312. this._samplingMode = samplingMode;
  15313. this._buffer = buffer;
  15314. this._deleteBuffer = deleteBuffer;
  15315. if (!url) {
  15316. return;
  15317. }
  15318. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  15319. if (!this._texture) {
  15320. if (!scene.useDelayedTextureLoading) {
  15321. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  15322. if (deleteBuffer) {
  15323. delete this._buffer;
  15324. }
  15325. }
  15326. else {
  15327. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15328. }
  15329. }
  15330. else {
  15331. BABYLON.Tools.SetImmediate(function () {
  15332. if (onLoad) {
  15333. onLoad();
  15334. }
  15335. });
  15336. }
  15337. }
  15338. Texture.prototype.delayLoad = function () {
  15339. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15340. return;
  15341. }
  15342. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15343. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  15344. if (!this._texture) {
  15345. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  15346. if (this._deleteBuffer) {
  15347. delete this._buffer;
  15348. }
  15349. }
  15350. };
  15351. Texture.prototype.updateSamplingMode = function (samplingMode) {
  15352. if (!this._texture) {
  15353. return;
  15354. }
  15355. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  15356. };
  15357. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  15358. x -= this.uOffset + 0.5;
  15359. y -= this.vOffset + 0.5;
  15360. z -= 0.5;
  15361. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  15362. t.x *= this.uScale;
  15363. t.y *= this.vScale;
  15364. t.x += 0.5;
  15365. t.y += 0.5;
  15366. t.z += 0.5;
  15367. };
  15368. Texture.prototype.getTextureMatrix = function () {
  15369. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng) {
  15370. return this._cachedTextureMatrix;
  15371. }
  15372. this._cachedUOffset = this.uOffset;
  15373. this._cachedVOffset = this.vOffset;
  15374. this._cachedUScale = this.uScale;
  15375. this._cachedVScale = this.vScale;
  15376. this._cachedUAng = this.uAng;
  15377. this._cachedVAng = this.vAng;
  15378. this._cachedWAng = this.wAng;
  15379. if (!this._cachedTextureMatrix) {
  15380. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  15381. this._rowGenerationMatrix = new BABYLON.Matrix();
  15382. this._t0 = BABYLON.Vector3.Zero();
  15383. this._t1 = BABYLON.Vector3.Zero();
  15384. this._t2 = BABYLON.Vector3.Zero();
  15385. }
  15386. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  15387. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  15388. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  15389. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  15390. this._t1.subtractInPlace(this._t0);
  15391. this._t2.subtractInPlace(this._t0);
  15392. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15393. this._cachedTextureMatrix.m[0] = this._t1.x;
  15394. this._cachedTextureMatrix.m[1] = this._t1.y;
  15395. this._cachedTextureMatrix.m[2] = this._t1.z;
  15396. this._cachedTextureMatrix.m[4] = this._t2.x;
  15397. this._cachedTextureMatrix.m[5] = this._t2.y;
  15398. this._cachedTextureMatrix.m[6] = this._t2.z;
  15399. this._cachedTextureMatrix.m[8] = this._t0.x;
  15400. this._cachedTextureMatrix.m[9] = this._t0.y;
  15401. this._cachedTextureMatrix.m[10] = this._t0.z;
  15402. return this._cachedTextureMatrix;
  15403. };
  15404. Texture.prototype.getReflectionTextureMatrix = function () {
  15405. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  15406. return this._cachedTextureMatrix;
  15407. }
  15408. if (!this._cachedTextureMatrix) {
  15409. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  15410. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  15411. }
  15412. this._cachedCoordinatesMode = this.coordinatesMode;
  15413. switch (this.coordinatesMode) {
  15414. case Texture.SPHERICAL_MODE:
  15415. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15416. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  15417. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  15418. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  15419. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  15420. break;
  15421. case Texture.PLANAR_MODE:
  15422. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15423. this._cachedTextureMatrix[0] = this.uScale;
  15424. this._cachedTextureMatrix[5] = this.vScale;
  15425. this._cachedTextureMatrix[12] = this.uOffset;
  15426. this._cachedTextureMatrix[13] = this.vOffset;
  15427. break;
  15428. case Texture.PROJECTION_MODE:
  15429. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  15430. this._projectionModeMatrix.m[0] = 0.5;
  15431. this._projectionModeMatrix.m[5] = -0.5;
  15432. this._projectionModeMatrix.m[10] = 0.0;
  15433. this._projectionModeMatrix.m[12] = 0.5;
  15434. this._projectionModeMatrix.m[13] = 0.5;
  15435. this._projectionModeMatrix.m[14] = 1.0;
  15436. this._projectionModeMatrix.m[15] = 1.0;
  15437. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  15438. break;
  15439. default:
  15440. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  15441. break;
  15442. }
  15443. return this._cachedTextureMatrix;
  15444. };
  15445. Texture.prototype.clone = function () {
  15446. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  15447. // Base texture
  15448. newTexture.hasAlpha = this.hasAlpha;
  15449. newTexture.level = this.level;
  15450. newTexture.wrapU = this.wrapU;
  15451. newTexture.wrapV = this.wrapV;
  15452. newTexture.coordinatesIndex = this.coordinatesIndex;
  15453. newTexture.coordinatesMode = this.coordinatesMode;
  15454. // Texture
  15455. newTexture.uOffset = this.uOffset;
  15456. newTexture.vOffset = this.vOffset;
  15457. newTexture.uScale = this.uScale;
  15458. newTexture.vScale = this.vScale;
  15459. newTexture.uAng = this.uAng;
  15460. newTexture.vAng = this.vAng;
  15461. newTexture.wAng = this.wAng;
  15462. return newTexture;
  15463. };
  15464. // Statics
  15465. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  15466. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  15467. if (onLoad === void 0) { onLoad = null; }
  15468. if (onError === void 0) { onError = null; }
  15469. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  15470. };
  15471. // Constants
  15472. Texture.NEAREST_SAMPLINGMODE = 1;
  15473. Texture.BILINEAR_SAMPLINGMODE = 2;
  15474. Texture.TRILINEAR_SAMPLINGMODE = 3;
  15475. Texture.EXPLICIT_MODE = 0;
  15476. Texture.SPHERICAL_MODE = 1;
  15477. Texture.PLANAR_MODE = 2;
  15478. Texture.CUBIC_MODE = 3;
  15479. Texture.PROJECTION_MODE = 4;
  15480. Texture.SKYBOX_MODE = 5;
  15481. Texture.CLAMP_ADDRESSMODE = 0;
  15482. Texture.WRAP_ADDRESSMODE = 1;
  15483. Texture.MIRROR_ADDRESSMODE = 2;
  15484. return Texture;
  15485. })(BABYLON.BaseTexture);
  15486. BABYLON.Texture = Texture;
  15487. })(BABYLON || (BABYLON = {}));
  15488. //# sourceMappingURL=babylon.texture.js.map
  15489. var __extends = this.__extends || function (d, b) {
  15490. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15491. function __() { this.constructor = d; }
  15492. __.prototype = b.prototype;
  15493. d.prototype = new __();
  15494. };
  15495. var BABYLON;
  15496. (function (BABYLON) {
  15497. var CubeTexture = (function (_super) {
  15498. __extends(CubeTexture, _super);
  15499. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  15500. _super.call(this, scene);
  15501. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  15502. this.name = rootUrl;
  15503. this.url = rootUrl;
  15504. this._noMipmap = noMipmap;
  15505. this.hasAlpha = false;
  15506. this._texture = this._getFromCache(rootUrl, noMipmap);
  15507. if (!extensions) {
  15508. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  15509. }
  15510. this._extensions = extensions;
  15511. if (!this._texture) {
  15512. if (!scene.useDelayedTextureLoading) {
  15513. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  15514. }
  15515. else {
  15516. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  15517. }
  15518. }
  15519. this.isCube = true;
  15520. this._textureMatrix = BABYLON.Matrix.Identity();
  15521. }
  15522. CubeTexture.prototype.clone = function () {
  15523. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  15524. // Base texture
  15525. newTexture.level = this.level;
  15526. newTexture.wrapU = this.wrapU;
  15527. newTexture.wrapV = this.wrapV;
  15528. newTexture.coordinatesIndex = this.coordinatesIndex;
  15529. newTexture.coordinatesMode = this.coordinatesMode;
  15530. return newTexture;
  15531. };
  15532. // Methods
  15533. CubeTexture.prototype.delayLoad = function () {
  15534. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15535. return;
  15536. }
  15537. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15538. this._texture = this._getFromCache(this.url, this._noMipmap);
  15539. if (!this._texture) {
  15540. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  15541. }
  15542. };
  15543. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  15544. return this._textureMatrix;
  15545. };
  15546. return CubeTexture;
  15547. })(BABYLON.BaseTexture);
  15548. BABYLON.CubeTexture = CubeTexture;
  15549. })(BABYLON || (BABYLON = {}));
  15550. //# sourceMappingURL=babylon.cubeTexture.js.map
  15551. var __extends = this.__extends || function (d, b) {
  15552. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15553. function __() { this.constructor = d; }
  15554. __.prototype = b.prototype;
  15555. d.prototype = new __();
  15556. };
  15557. var BABYLON;
  15558. (function (BABYLON) {
  15559. var RenderTargetTexture = (function (_super) {
  15560. __extends(RenderTargetTexture, _super);
  15561. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  15562. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  15563. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  15564. _super.call(this, null, scene, !generateMipMaps);
  15565. this.renderList = new Array();
  15566. this.renderParticles = true;
  15567. this.renderSprites = false;
  15568. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  15569. this._currentRefreshId = -1;
  15570. this._refreshRate = 1;
  15571. this.name = name;
  15572. this.isRenderTarget = true;
  15573. this._size = size;
  15574. this._generateMipMaps = generateMipMaps;
  15575. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  15576. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  15577. // Rendering groups
  15578. this._renderingManager = new BABYLON.RenderingManager(scene);
  15579. }
  15580. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  15581. this._currentRefreshId = -1;
  15582. };
  15583. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  15584. get: function () {
  15585. return this._refreshRate;
  15586. },
  15587. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  15588. set: function (value) {
  15589. this._refreshRate = value;
  15590. this.resetRefreshCounter();
  15591. },
  15592. enumerable: true,
  15593. configurable: true
  15594. });
  15595. RenderTargetTexture.prototype._shouldRender = function () {
  15596. if (this._currentRefreshId === -1) {
  15597. this._currentRefreshId = 1;
  15598. return true;
  15599. }
  15600. if (this.refreshRate === this._currentRefreshId) {
  15601. this._currentRefreshId = 1;
  15602. return true;
  15603. }
  15604. this._currentRefreshId++;
  15605. return false;
  15606. };
  15607. RenderTargetTexture.prototype.isReady = function () {
  15608. if (!this.getScene().renderTargetsEnabled) {
  15609. return false;
  15610. }
  15611. return _super.prototype.isReady.call(this);
  15612. };
  15613. RenderTargetTexture.prototype.getRenderSize = function () {
  15614. return this._size;
  15615. };
  15616. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  15617. get: function () {
  15618. return true;
  15619. },
  15620. enumerable: true,
  15621. configurable: true
  15622. });
  15623. RenderTargetTexture.prototype.scale = function (ratio) {
  15624. var newSize = this._size * ratio;
  15625. this.resize(newSize, this._generateMipMaps);
  15626. };
  15627. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  15628. this.releaseInternalTexture();
  15629. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  15630. };
  15631. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  15632. var scene = this.getScene();
  15633. var engine = scene.getEngine();
  15634. if (this._waitingRenderList) {
  15635. this.renderList = [];
  15636. for (var index = 0; index < this._waitingRenderList.length; index++) {
  15637. var id = this._waitingRenderList[index];
  15638. this.renderList.push(scene.getMeshByID(id));
  15639. }
  15640. delete this._waitingRenderList;
  15641. }
  15642. if (this.renderList && this.renderList.length === 0) {
  15643. return;
  15644. }
  15645. // Bind
  15646. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  15647. engine.bindFramebuffer(this._texture);
  15648. }
  15649. this._renderingManager.reset();
  15650. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  15651. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  15652. var mesh = currentRenderList[meshIndex];
  15653. if (mesh) {
  15654. if (!mesh.isReady()) {
  15655. // Reset _currentRefreshId
  15656. this.resetRefreshCounter();
  15657. continue;
  15658. }
  15659. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  15660. mesh._activate(scene.getRenderId());
  15661. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  15662. var subMesh = mesh.subMeshes[subIndex];
  15663. scene._activeIndices += subMesh.indexCount;
  15664. this._renderingManager.dispatch(subMesh);
  15665. }
  15666. }
  15667. }
  15668. }
  15669. if (this.onBeforeRender) {
  15670. this.onBeforeRender();
  15671. }
  15672. // Clear
  15673. if (this.onClear) {
  15674. this.onClear(engine);
  15675. }
  15676. else {
  15677. engine.clear(scene.clearColor, true, true);
  15678. }
  15679. if (!this._doNotChangeAspectRatio) {
  15680. scene.updateTransformMatrix(true);
  15681. }
  15682. // Render
  15683. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  15684. if (useCameraPostProcess) {
  15685. scene.postProcessManager._finalizeFrame(false, this._texture);
  15686. }
  15687. if (!this._doNotChangeAspectRatio) {
  15688. scene.updateTransformMatrix(true);
  15689. }
  15690. if (this.onAfterRender) {
  15691. this.onAfterRender();
  15692. }
  15693. // Dump ?
  15694. if (dumpForDebug) {
  15695. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  15696. }
  15697. // Unbind
  15698. engine.unBindFramebuffer(this._texture);
  15699. if (this.onAfterUnbind) {
  15700. this.onAfterUnbind();
  15701. }
  15702. };
  15703. RenderTargetTexture.prototype.clone = function () {
  15704. var textureSize = this.getSize();
  15705. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15706. // Base texture
  15707. newTexture.hasAlpha = this.hasAlpha;
  15708. newTexture.level = this.level;
  15709. // RenderTarget Texture
  15710. newTexture.coordinatesMode = this.coordinatesMode;
  15711. newTexture.renderList = this.renderList.slice(0);
  15712. return newTexture;
  15713. };
  15714. return RenderTargetTexture;
  15715. })(BABYLON.Texture);
  15716. BABYLON.RenderTargetTexture = RenderTargetTexture;
  15717. })(BABYLON || (BABYLON = {}));
  15718. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  15719. var __extends = this.__extends || function (d, b) {
  15720. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15721. function __() { this.constructor = d; }
  15722. __.prototype = b.prototype;
  15723. d.prototype = new __();
  15724. };
  15725. var BABYLON;
  15726. (function (BABYLON) {
  15727. var ProceduralTexture = (function (_super) {
  15728. __extends(ProceduralTexture, _super);
  15729. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  15730. if (generateMipMaps === void 0) { generateMipMaps = true; }
  15731. _super.call(this, null, scene, !generateMipMaps);
  15732. this._currentRefreshId = -1;
  15733. this._refreshRate = 1;
  15734. this._vertexDeclaration = [2];
  15735. this._vertexStrideSize = 2 * 4;
  15736. this._uniforms = new Array();
  15737. this._samplers = new Array();
  15738. this._textures = new Array();
  15739. this._floats = new Array();
  15740. this._floatsArrays = {};
  15741. this._colors3 = new Array();
  15742. this._colors4 = new Array();
  15743. this._vectors2 = new Array();
  15744. this._vectors3 = new Array();
  15745. this._matrices = new Array();
  15746. this._fallbackTextureUsed = false;
  15747. scene._proceduralTextures.push(this);
  15748. this.name = name;
  15749. this.isRenderTarget = true;
  15750. this._size = size;
  15751. this._generateMipMaps = generateMipMaps;
  15752. this.setFragment(fragment);
  15753. this._fallbackTexture = fallbackTexture;
  15754. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  15755. // VBO
  15756. var vertices = [];
  15757. vertices.push(1, 1);
  15758. vertices.push(-1, 1);
  15759. vertices.push(-1, -1);
  15760. vertices.push(1, -1);
  15761. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15762. // Indices
  15763. var indices = [];
  15764. indices.push(0);
  15765. indices.push(1);
  15766. indices.push(2);
  15767. indices.push(0);
  15768. indices.push(2);
  15769. indices.push(3);
  15770. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15771. }
  15772. ProceduralTexture.prototype.reset = function () {
  15773. if (this._effect === undefined) {
  15774. return;
  15775. }
  15776. var engine = this.getScene().getEngine();
  15777. engine._releaseEffect(this._effect);
  15778. };
  15779. ProceduralTexture.prototype.isReady = function () {
  15780. var _this = this;
  15781. var engine = this.getScene().getEngine();
  15782. var shaders;
  15783. if (!this._fragment) {
  15784. return false;
  15785. }
  15786. if (this._fallbackTextureUsed) {
  15787. return true;
  15788. }
  15789. if (this._fragment.fragmentElement !== undefined) {
  15790. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  15791. }
  15792. else {
  15793. shaders = { vertex: "procedural", fragment: this._fragment };
  15794. }
  15795. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  15796. _this.releaseInternalTexture();
  15797. if (_this._fallbackTexture) {
  15798. _this._texture = _this._fallbackTexture._texture;
  15799. _this._texture.references++;
  15800. }
  15801. _this._fallbackTextureUsed = true;
  15802. });
  15803. return this._effect.isReady();
  15804. };
  15805. ProceduralTexture.prototype.resetRefreshCounter = function () {
  15806. this._currentRefreshId = -1;
  15807. };
  15808. ProceduralTexture.prototype.setFragment = function (fragment) {
  15809. this._fragment = fragment;
  15810. };
  15811. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  15812. get: function () {
  15813. return this._refreshRate;
  15814. },
  15815. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  15816. set: function (value) {
  15817. this._refreshRate = value;
  15818. this.resetRefreshCounter();
  15819. },
  15820. enumerable: true,
  15821. configurable: true
  15822. });
  15823. ProceduralTexture.prototype._shouldRender = function () {
  15824. if (!this.isReady() || !this._texture) {
  15825. return false;
  15826. }
  15827. if (this._fallbackTextureUsed) {
  15828. return false;
  15829. }
  15830. if (this._currentRefreshId === -1) {
  15831. this._currentRefreshId = 1;
  15832. return true;
  15833. }
  15834. if (this.refreshRate === this._currentRefreshId) {
  15835. this._currentRefreshId = 1;
  15836. return true;
  15837. }
  15838. this._currentRefreshId++;
  15839. return false;
  15840. };
  15841. ProceduralTexture.prototype.getRenderSize = function () {
  15842. return this._size;
  15843. };
  15844. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  15845. if (this._fallbackTextureUsed) {
  15846. return;
  15847. }
  15848. this.releaseInternalTexture();
  15849. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  15850. };
  15851. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  15852. if (this._uniforms.indexOf(uniformName) === -1) {
  15853. this._uniforms.push(uniformName);
  15854. }
  15855. };
  15856. ProceduralTexture.prototype.setTexture = function (name, texture) {
  15857. if (this._samplers.indexOf(name) === -1) {
  15858. this._samplers.push(name);
  15859. }
  15860. this._textures[name] = texture;
  15861. return this;
  15862. };
  15863. ProceduralTexture.prototype.setFloat = function (name, value) {
  15864. this._checkUniform(name);
  15865. this._floats[name] = value;
  15866. return this;
  15867. };
  15868. ProceduralTexture.prototype.setFloats = function (name, value) {
  15869. this._checkUniform(name);
  15870. this._floatsArrays[name] = value;
  15871. return this;
  15872. };
  15873. ProceduralTexture.prototype.setColor3 = function (name, value) {
  15874. this._checkUniform(name);
  15875. this._colors3[name] = value;
  15876. return this;
  15877. };
  15878. ProceduralTexture.prototype.setColor4 = function (name, value) {
  15879. this._checkUniform(name);
  15880. this._colors4[name] = value;
  15881. return this;
  15882. };
  15883. ProceduralTexture.prototype.setVector2 = function (name, value) {
  15884. this._checkUniform(name);
  15885. this._vectors2[name] = value;
  15886. return this;
  15887. };
  15888. ProceduralTexture.prototype.setVector3 = function (name, value) {
  15889. this._checkUniform(name);
  15890. this._vectors3[name] = value;
  15891. return this;
  15892. };
  15893. ProceduralTexture.prototype.setMatrix = function (name, value) {
  15894. this._checkUniform(name);
  15895. this._matrices[name] = value;
  15896. return this;
  15897. };
  15898. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  15899. var scene = this.getScene();
  15900. var engine = scene.getEngine();
  15901. engine.bindFramebuffer(this._texture);
  15902. // Clear
  15903. engine.clear(scene.clearColor, true, true);
  15904. // Render
  15905. engine.enableEffect(this._effect);
  15906. engine.setState(false);
  15907. for (var name in this._textures) {
  15908. this._effect.setTexture(name, this._textures[name]);
  15909. }
  15910. for (name in this._floats) {
  15911. this._effect.setFloat(name, this._floats[name]);
  15912. }
  15913. for (name in this._floatsArrays) {
  15914. this._effect.setArray(name, this._floatsArrays[name]);
  15915. }
  15916. for (name in this._colors3) {
  15917. this._effect.setColor3(name, this._colors3[name]);
  15918. }
  15919. for (name in this._colors4) {
  15920. var color = this._colors4[name];
  15921. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  15922. }
  15923. for (name in this._vectors2) {
  15924. this._effect.setVector2(name, this._vectors2[name]);
  15925. }
  15926. for (name in this._vectors3) {
  15927. this._effect.setVector3(name, this._vectors3[name]);
  15928. }
  15929. for (name in this._matrices) {
  15930. this._effect.setMatrix(name, this._matrices[name]);
  15931. }
  15932. // VBOs
  15933. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15934. // Draw order
  15935. engine.draw(true, 0, 6);
  15936. // Unbind
  15937. engine.unBindFramebuffer(this._texture);
  15938. };
  15939. ProceduralTexture.prototype.clone = function () {
  15940. var textureSize = this.getSize();
  15941. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  15942. // Base texture
  15943. newTexture.hasAlpha = this.hasAlpha;
  15944. newTexture.level = this.level;
  15945. // RenderTarget Texture
  15946. newTexture.coordinatesMode = this.coordinatesMode;
  15947. return newTexture;
  15948. };
  15949. ProceduralTexture.prototype.dispose = function () {
  15950. var index = this.getScene()._proceduralTextures.indexOf(this);
  15951. if (index >= 0) {
  15952. this.getScene()._proceduralTextures.splice(index, 1);
  15953. }
  15954. _super.prototype.dispose.call(this);
  15955. };
  15956. return ProceduralTexture;
  15957. })(BABYLON.Texture);
  15958. BABYLON.ProceduralTexture = ProceduralTexture;
  15959. })(BABYLON || (BABYLON = {}));
  15960. //# sourceMappingURL=babylon.proceduralTexture.js.map
  15961. var __extends = this.__extends || function (d, b) {
  15962. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  15963. function __() { this.constructor = d; }
  15964. __.prototype = b.prototype;
  15965. d.prototype = new __();
  15966. };
  15967. var BABYLON;
  15968. (function (BABYLON) {
  15969. var MirrorTexture = (function (_super) {
  15970. __extends(MirrorTexture, _super);
  15971. function MirrorTexture(name, size, scene, generateMipMaps) {
  15972. var _this = this;
  15973. _super.call(this, name, size, scene, generateMipMaps, true);
  15974. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  15975. this._transformMatrix = BABYLON.Matrix.Zero();
  15976. this._mirrorMatrix = BABYLON.Matrix.Zero();
  15977. this.onBeforeRender = function () {
  15978. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  15979. _this._savedViewMatrix = scene.getViewMatrix();
  15980. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  15981. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  15982. scene.clipPlane = _this.mirrorPlane;
  15983. scene.getEngine().cullBackFaces = false;
  15984. };
  15985. this.onAfterRender = function () {
  15986. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  15987. scene.getEngine().cullBackFaces = true;
  15988. delete scene.clipPlane;
  15989. };
  15990. }
  15991. MirrorTexture.prototype.clone = function () {
  15992. var textureSize = this.getSize();
  15993. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  15994. // Base texture
  15995. newTexture.hasAlpha = this.hasAlpha;
  15996. newTexture.level = this.level;
  15997. // Mirror Texture
  15998. newTexture.mirrorPlane = this.mirrorPlane.clone();
  15999. newTexture.renderList = this.renderList.slice(0);
  16000. return newTexture;
  16001. };
  16002. return MirrorTexture;
  16003. })(BABYLON.RenderTargetTexture);
  16004. BABYLON.MirrorTexture = MirrorTexture;
  16005. })(BABYLON || (BABYLON = {}));
  16006. //# sourceMappingURL=babylon.mirrorTexture.js.map
  16007. var __extends = this.__extends || function (d, b) {
  16008. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16009. function __() { this.constructor = d; }
  16010. __.prototype = b.prototype;
  16011. d.prototype = new __();
  16012. };
  16013. var BABYLON;
  16014. (function (BABYLON) {
  16015. var DynamicTexture = (function (_super) {
  16016. __extends(DynamicTexture, _super);
  16017. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  16018. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16019. _super.call(this, null, scene, !generateMipMaps);
  16020. this.name = name;
  16021. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16022. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16023. this._generateMipMaps = generateMipMaps;
  16024. if (options.getContext) {
  16025. this._canvas = options;
  16026. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16027. }
  16028. else {
  16029. this._canvas = document.createElement("canvas");
  16030. if (options.width) {
  16031. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16032. }
  16033. else {
  16034. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  16035. }
  16036. }
  16037. var textureSize = this.getSize();
  16038. this._canvas.width = textureSize.width;
  16039. this._canvas.height = textureSize.height;
  16040. this._context = this._canvas.getContext("2d");
  16041. }
  16042. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  16043. get: function () {
  16044. return true;
  16045. },
  16046. enumerable: true,
  16047. configurable: true
  16048. });
  16049. DynamicTexture.prototype.scale = function (ratio) {
  16050. var textureSize = this.getSize();
  16051. textureSize.width *= ratio;
  16052. textureSize.height *= ratio;
  16053. this._canvas.width = textureSize.width;
  16054. this._canvas.height = textureSize.height;
  16055. this.releaseInternalTexture();
  16056. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  16057. };
  16058. DynamicTexture.prototype.getContext = function () {
  16059. return this._context;
  16060. };
  16061. DynamicTexture.prototype.clear = function () {
  16062. var size = this.getSize();
  16063. this._context.fillRect(0, 0, size.width, size.height);
  16064. };
  16065. DynamicTexture.prototype.update = function (invertY) {
  16066. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  16067. };
  16068. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  16069. if (update === void 0) { update = true; }
  16070. var size = this.getSize();
  16071. if (clearColor) {
  16072. this._context.fillStyle = clearColor;
  16073. this._context.fillRect(0, 0, size.width, size.height);
  16074. }
  16075. this._context.font = font;
  16076. if (x === null) {
  16077. var textSize = this._context.measureText(text);
  16078. x = (size.width - textSize.width) / 2;
  16079. }
  16080. this._context.fillStyle = color;
  16081. this._context.fillText(text, x, y);
  16082. if (update) {
  16083. this.update(invertY);
  16084. }
  16085. };
  16086. DynamicTexture.prototype.clone = function () {
  16087. var textureSize = this.getSize();
  16088. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16089. // Base texture
  16090. newTexture.hasAlpha = this.hasAlpha;
  16091. newTexture.level = this.level;
  16092. // Dynamic Texture
  16093. newTexture.wrapU = this.wrapU;
  16094. newTexture.wrapV = this.wrapV;
  16095. return newTexture;
  16096. };
  16097. return DynamicTexture;
  16098. })(BABYLON.Texture);
  16099. BABYLON.DynamicTexture = DynamicTexture;
  16100. })(BABYLON || (BABYLON = {}));
  16101. //# sourceMappingURL=babylon.dynamicTexture.js.map
  16102. var __extends = this.__extends || function (d, b) {
  16103. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16104. function __() { this.constructor = d; }
  16105. __.prototype = b.prototype;
  16106. d.prototype = new __();
  16107. };
  16108. var BABYLON;
  16109. (function (BABYLON) {
  16110. var VideoTexture = (function (_super) {
  16111. __extends(VideoTexture, _super);
  16112. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  16113. var _this = this;
  16114. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16115. _super.call(this, null, scene, !generateMipMaps, invertY);
  16116. this._autoLaunch = true;
  16117. this.name = name;
  16118. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16119. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16120. var requiredWidth = size.width || size;
  16121. var requiredHeight = size.height || size;
  16122. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  16123. var textureSize = this.getSize();
  16124. this.video = document.createElement("video");
  16125. this.video.width = textureSize.width;
  16126. this.video.height = textureSize.height;
  16127. this.video.autoplay = false;
  16128. this.video.loop = true;
  16129. this.video.addEventListener("canplaythrough", function () {
  16130. if (_this._texture) {
  16131. _this._texture.isReady = true;
  16132. }
  16133. });
  16134. urls.forEach(function (url) {
  16135. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  16136. var source = document.createElement("source");
  16137. source.src = url;
  16138. _this.video.appendChild(source);
  16139. });
  16140. this._lastUpdate = BABYLON.Tools.Now;
  16141. }
  16142. VideoTexture.prototype.update = function () {
  16143. if (this._autoLaunch) {
  16144. this._autoLaunch = false;
  16145. this.video.play();
  16146. }
  16147. var now = BABYLON.Tools.Now;
  16148. if (now - this._lastUpdate < 15) {
  16149. return false;
  16150. }
  16151. this._lastUpdate = now;
  16152. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  16153. return true;
  16154. };
  16155. return VideoTexture;
  16156. })(BABYLON.Texture);
  16157. BABYLON.VideoTexture = VideoTexture;
  16158. })(BABYLON || (BABYLON = {}));
  16159. //# sourceMappingURL=babylon.videoTexture.js.map
  16160. var __extends = this.__extends || function (d, b) {
  16161. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16162. function __() { this.constructor = d; }
  16163. __.prototype = b.prototype;
  16164. d.prototype = new __();
  16165. };
  16166. var BABYLON;
  16167. (function (BABYLON) {
  16168. var CustomProceduralTexture = (function (_super) {
  16169. __extends(CustomProceduralTexture, _super);
  16170. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  16171. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  16172. this._animate = true;
  16173. this._time = 0;
  16174. this._texturePath = texturePath;
  16175. //Try to load json
  16176. this.loadJson(texturePath);
  16177. this.refreshRate = 1;
  16178. }
  16179. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  16180. var _this = this;
  16181. var that = this;
  16182. function noConfigFile() {
  16183. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  16184. try {
  16185. that.setFragment(that._texturePath);
  16186. }
  16187. catch (ex) {
  16188. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  16189. }
  16190. }
  16191. var configFileUrl = jsonUrl + "/config.json";
  16192. var xhr = new XMLHttpRequest();
  16193. xhr.open("GET", configFileUrl, true);
  16194. xhr.addEventListener("load", function () {
  16195. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  16196. try {
  16197. _this._config = JSON.parse(xhr.response);
  16198. _this.updateShaderUniforms();
  16199. _this.updateTextures();
  16200. _this.setFragment(_this._texturePath + "/custom");
  16201. _this._animate = _this._config.animate;
  16202. _this.refreshRate = _this._config.refreshrate;
  16203. }
  16204. catch (ex) {
  16205. noConfigFile();
  16206. }
  16207. }
  16208. else {
  16209. noConfigFile();
  16210. }
  16211. }, false);
  16212. xhr.addEventListener("error", function () {
  16213. noConfigFile();
  16214. }, false);
  16215. try {
  16216. xhr.send();
  16217. }
  16218. catch (ex) {
  16219. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  16220. }
  16221. };
  16222. CustomProceduralTexture.prototype.isReady = function () {
  16223. if (!_super.prototype.isReady.call(this)) {
  16224. return false;
  16225. }
  16226. for (var name in this._textures) {
  16227. var texture = this._textures[name];
  16228. if (!texture.isReady()) {
  16229. return false;
  16230. }
  16231. }
  16232. return true;
  16233. };
  16234. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16235. if (this._animate) {
  16236. this._time += this.getScene().getAnimationRatio() * 0.03;
  16237. this.updateShaderUniforms();
  16238. }
  16239. _super.prototype.render.call(this, useCameraPostProcess);
  16240. };
  16241. CustomProceduralTexture.prototype.updateTextures = function () {
  16242. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  16243. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  16244. }
  16245. };
  16246. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  16247. if (this._config) {
  16248. for (var j = 0; j < this._config.uniforms.length; j++) {
  16249. var uniform = this._config.uniforms[j];
  16250. switch (uniform.type) {
  16251. case "float":
  16252. this.setFloat(uniform.name, uniform.value);
  16253. break;
  16254. case "color3":
  16255. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  16256. break;
  16257. case "color4":
  16258. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  16259. break;
  16260. case "vector2":
  16261. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  16262. break;
  16263. case "vector3":
  16264. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  16265. break;
  16266. }
  16267. }
  16268. }
  16269. this.setFloat("time", this._time);
  16270. };
  16271. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  16272. get: function () {
  16273. return this._animate;
  16274. },
  16275. set: function (value) {
  16276. this._animate = value;
  16277. },
  16278. enumerable: true,
  16279. configurable: true
  16280. });
  16281. return CustomProceduralTexture;
  16282. })(BABYLON.ProceduralTexture);
  16283. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  16284. })(BABYLON || (BABYLON = {}));
  16285. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  16286. var __extends = this.__extends || function (d, b) {
  16287. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16288. function __() { this.constructor = d; }
  16289. __.prototype = b.prototype;
  16290. d.prototype = new __();
  16291. };
  16292. var BABYLON;
  16293. (function (BABYLON) {
  16294. var WoodProceduralTexture = (function (_super) {
  16295. __extends(WoodProceduralTexture, _super);
  16296. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16297. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  16298. this._ampScale = 100.0;
  16299. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  16300. this.updateShaderUniforms();
  16301. this.refreshRate = 0;
  16302. }
  16303. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  16304. this.setFloat("ampScale", this._ampScale);
  16305. this.setColor3("woodColor", this._woodColor);
  16306. };
  16307. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  16308. get: function () {
  16309. return this._ampScale;
  16310. },
  16311. set: function (value) {
  16312. this._ampScale = value;
  16313. this.updateShaderUniforms();
  16314. },
  16315. enumerable: true,
  16316. configurable: true
  16317. });
  16318. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  16319. get: function () {
  16320. return this._woodColor;
  16321. },
  16322. set: function (value) {
  16323. this._woodColor = value;
  16324. this.updateShaderUniforms();
  16325. },
  16326. enumerable: true,
  16327. configurable: true
  16328. });
  16329. return WoodProceduralTexture;
  16330. })(BABYLON.ProceduralTexture);
  16331. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  16332. var FireProceduralTexture = (function (_super) {
  16333. __extends(FireProceduralTexture, _super);
  16334. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16335. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  16336. this._time = 0.0;
  16337. this._speed = new BABYLON.Vector2(0.5, 0.3);
  16338. this._autoGenerateTime = true;
  16339. this._alphaThreshold = 0.5;
  16340. this._fireColors = FireProceduralTexture.RedFireColors;
  16341. this.updateShaderUniforms();
  16342. this.refreshRate = 1;
  16343. }
  16344. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  16345. this.setFloat("time", this._time);
  16346. this.setVector2("speed", this._speed);
  16347. this.setColor3("c1", this._fireColors[0]);
  16348. this.setColor3("c2", this._fireColors[1]);
  16349. this.setColor3("c3", this._fireColors[2]);
  16350. this.setColor3("c4", this._fireColors[3]);
  16351. this.setColor3("c5", this._fireColors[4]);
  16352. this.setColor3("c6", this._fireColors[5]);
  16353. this.setFloat("alphaThreshold", this._alphaThreshold);
  16354. };
  16355. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16356. if (this._autoGenerateTime) {
  16357. this._time += this.getScene().getAnimationRatio() * 0.03;
  16358. this.updateShaderUniforms();
  16359. }
  16360. _super.prototype.render.call(this, useCameraPostProcess);
  16361. };
  16362. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  16363. get: function () {
  16364. return [
  16365. new BABYLON.Color3(0.5, 0.0, 1.0),
  16366. new BABYLON.Color3(0.9, 0.0, 1.0),
  16367. new BABYLON.Color3(0.2, 0.0, 1.0),
  16368. new BABYLON.Color3(1.0, 0.9, 1.0),
  16369. new BABYLON.Color3(0.1, 0.1, 1.0),
  16370. new BABYLON.Color3(0.9, 0.9, 1.0)
  16371. ];
  16372. },
  16373. enumerable: true,
  16374. configurable: true
  16375. });
  16376. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  16377. get: function () {
  16378. return [
  16379. new BABYLON.Color3(0.5, 1.0, 0.0),
  16380. new BABYLON.Color3(0.5, 1.0, 0.0),
  16381. new BABYLON.Color3(0.3, 0.4, 0.0),
  16382. new BABYLON.Color3(0.5, 1.0, 0.0),
  16383. new BABYLON.Color3(0.2, 0.0, 0.0),
  16384. new BABYLON.Color3(0.5, 1.0, 0.0)
  16385. ];
  16386. },
  16387. enumerable: true,
  16388. configurable: true
  16389. });
  16390. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  16391. get: function () {
  16392. return [
  16393. new BABYLON.Color3(0.5, 0.0, 0.1),
  16394. new BABYLON.Color3(0.9, 0.0, 0.0),
  16395. new BABYLON.Color3(0.2, 0.0, 0.0),
  16396. new BABYLON.Color3(1.0, 0.9, 0.0),
  16397. new BABYLON.Color3(0.1, 0.1, 0.1),
  16398. new BABYLON.Color3(0.9, 0.9, 0.9)
  16399. ];
  16400. },
  16401. enumerable: true,
  16402. configurable: true
  16403. });
  16404. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  16405. get: function () {
  16406. return [
  16407. new BABYLON.Color3(0.1, 0.0, 0.5),
  16408. new BABYLON.Color3(0.0, 0.0, 0.5),
  16409. new BABYLON.Color3(0.1, 0.0, 0.2),
  16410. new BABYLON.Color3(0.0, 0.0, 1.0),
  16411. new BABYLON.Color3(0.1, 0.2, 0.3),
  16412. new BABYLON.Color3(0.0, 0.2, 0.9)
  16413. ];
  16414. },
  16415. enumerable: true,
  16416. configurable: true
  16417. });
  16418. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  16419. get: function () {
  16420. return this._fireColors;
  16421. },
  16422. set: function (value) {
  16423. this._fireColors = value;
  16424. this.updateShaderUniforms();
  16425. },
  16426. enumerable: true,
  16427. configurable: true
  16428. });
  16429. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  16430. get: function () {
  16431. return this._time;
  16432. },
  16433. set: function (value) {
  16434. this._time = value;
  16435. this.updateShaderUniforms();
  16436. },
  16437. enumerable: true,
  16438. configurable: true
  16439. });
  16440. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  16441. get: function () {
  16442. return this._speed;
  16443. },
  16444. set: function (value) {
  16445. this._speed = value;
  16446. this.updateShaderUniforms();
  16447. },
  16448. enumerable: true,
  16449. configurable: true
  16450. });
  16451. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  16452. get: function () {
  16453. return this._alphaThreshold;
  16454. },
  16455. set: function (value) {
  16456. this._alphaThreshold = value;
  16457. this.updateShaderUniforms();
  16458. },
  16459. enumerable: true,
  16460. configurable: true
  16461. });
  16462. return FireProceduralTexture;
  16463. })(BABYLON.ProceduralTexture);
  16464. BABYLON.FireProceduralTexture = FireProceduralTexture;
  16465. var CloudProceduralTexture = (function (_super) {
  16466. __extends(CloudProceduralTexture, _super);
  16467. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16468. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  16469. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  16470. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  16471. this.updateShaderUniforms();
  16472. this.refreshRate = 0;
  16473. }
  16474. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  16475. this.setColor3("skyColor", this._skyColor);
  16476. this.setColor3("cloudColor", this._cloudColor);
  16477. };
  16478. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  16479. get: function () {
  16480. return this._skyColor;
  16481. },
  16482. set: function (value) {
  16483. this._skyColor = value;
  16484. this.updateShaderUniforms();
  16485. },
  16486. enumerable: true,
  16487. configurable: true
  16488. });
  16489. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  16490. get: function () {
  16491. return this._cloudColor;
  16492. },
  16493. set: function (value) {
  16494. this._cloudColor = value;
  16495. this.updateShaderUniforms();
  16496. },
  16497. enumerable: true,
  16498. configurable: true
  16499. });
  16500. return CloudProceduralTexture;
  16501. })(BABYLON.ProceduralTexture);
  16502. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  16503. var GrassProceduralTexture = (function (_super) {
  16504. __extends(GrassProceduralTexture, _super);
  16505. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16506. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  16507. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  16508. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  16509. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  16510. this._groundColor = new BABYLON.Color3(1, 1, 1);
  16511. this._grassColors = [
  16512. new BABYLON.Color3(0.29, 0.38, 0.02),
  16513. new BABYLON.Color3(0.36, 0.49, 0.09),
  16514. new BABYLON.Color3(0.51, 0.6, 0.28)
  16515. ];
  16516. this.updateShaderUniforms();
  16517. this.refreshRate = 0;
  16518. }
  16519. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  16520. this.setColor3("herb1Color", this._grassColors[0]);
  16521. this.setColor3("herb2Color", this._grassColors[1]);
  16522. this.setColor3("herb3Color", this._grassColors[2]);
  16523. this.setColor3("groundColor", this._groundColor);
  16524. };
  16525. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  16526. get: function () {
  16527. return this._grassColors;
  16528. },
  16529. set: function (value) {
  16530. this._grassColors = value;
  16531. this.updateShaderUniforms();
  16532. },
  16533. enumerable: true,
  16534. configurable: true
  16535. });
  16536. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  16537. get: function () {
  16538. return this._groundColor;
  16539. },
  16540. set: function (value) {
  16541. this.groundColor = value;
  16542. this.updateShaderUniforms();
  16543. },
  16544. enumerable: true,
  16545. configurable: true
  16546. });
  16547. return GrassProceduralTexture;
  16548. })(BABYLON.ProceduralTexture);
  16549. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  16550. var RoadProceduralTexture = (function (_super) {
  16551. __extends(RoadProceduralTexture, _super);
  16552. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16553. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  16554. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  16555. this.updateShaderUniforms();
  16556. this.refreshRate = 0;
  16557. }
  16558. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  16559. this.setColor3("roadColor", this._roadColor);
  16560. };
  16561. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  16562. get: function () {
  16563. return this._roadColor;
  16564. },
  16565. set: function (value) {
  16566. this._roadColor = value;
  16567. this.updateShaderUniforms();
  16568. },
  16569. enumerable: true,
  16570. configurable: true
  16571. });
  16572. return RoadProceduralTexture;
  16573. })(BABYLON.ProceduralTexture);
  16574. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  16575. var BrickProceduralTexture = (function (_super) {
  16576. __extends(BrickProceduralTexture, _super);
  16577. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16578. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  16579. this._numberOfBricksHeight = 15;
  16580. this._numberOfBricksWidth = 5;
  16581. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  16582. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  16583. this.updateShaderUniforms();
  16584. this.refreshRate = 0;
  16585. }
  16586. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  16587. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  16588. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  16589. this.setColor3("brickColor", this._brickColor);
  16590. this.setColor3("jointColor", this._jointColor);
  16591. };
  16592. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  16593. get: function () {
  16594. return this._numberOfBricksHeight;
  16595. },
  16596. set: function (value) {
  16597. this._numberOfBricksHeight = value;
  16598. this.updateShaderUniforms();
  16599. },
  16600. enumerable: true,
  16601. configurable: true
  16602. });
  16603. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  16604. get: function () {
  16605. return this._numberOfBricksWidth;
  16606. },
  16607. set: function (value) {
  16608. this._numberOfBricksHeight = value;
  16609. this.updateShaderUniforms();
  16610. },
  16611. enumerable: true,
  16612. configurable: true
  16613. });
  16614. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  16615. get: function () {
  16616. return this._jointColor;
  16617. },
  16618. set: function (value) {
  16619. this._jointColor = value;
  16620. this.updateShaderUniforms();
  16621. },
  16622. enumerable: true,
  16623. configurable: true
  16624. });
  16625. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  16626. get: function () {
  16627. return this._brickColor;
  16628. },
  16629. set: function (value) {
  16630. this._brickColor = value;
  16631. this.updateShaderUniforms();
  16632. },
  16633. enumerable: true,
  16634. configurable: true
  16635. });
  16636. return BrickProceduralTexture;
  16637. })(BABYLON.ProceduralTexture);
  16638. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  16639. var MarbleProceduralTexture = (function (_super) {
  16640. __extends(MarbleProceduralTexture, _super);
  16641. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16642. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  16643. this._numberOfTilesHeight = 3;
  16644. this._numberOfTilesWidth = 3;
  16645. this._amplitude = 9.0;
  16646. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  16647. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  16648. this.updateShaderUniforms();
  16649. this.refreshRate = 0;
  16650. }
  16651. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  16652. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  16653. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  16654. this.setFloat("amplitude", this._amplitude);
  16655. this.setColor3("marbleColor", this._marbleColor);
  16656. this.setColor3("jointColor", this._jointColor);
  16657. };
  16658. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  16659. get: function () {
  16660. return this._numberOfTilesHeight;
  16661. },
  16662. set: function (value) {
  16663. this._numberOfTilesHeight = value;
  16664. this.updateShaderUniforms();
  16665. },
  16666. enumerable: true,
  16667. configurable: true
  16668. });
  16669. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  16670. get: function () {
  16671. return this._numberOfTilesWidth;
  16672. },
  16673. set: function (value) {
  16674. this._numberOfTilesWidth = value;
  16675. this.updateShaderUniforms();
  16676. },
  16677. enumerable: true,
  16678. configurable: true
  16679. });
  16680. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  16681. get: function () {
  16682. return this._jointColor;
  16683. },
  16684. set: function (value) {
  16685. this._jointColor = value;
  16686. this.updateShaderUniforms();
  16687. },
  16688. enumerable: true,
  16689. configurable: true
  16690. });
  16691. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  16692. get: function () {
  16693. return this._marbleColor;
  16694. },
  16695. set: function (value) {
  16696. this._marbleColor = value;
  16697. this.updateShaderUniforms();
  16698. },
  16699. enumerable: true,
  16700. configurable: true
  16701. });
  16702. return MarbleProceduralTexture;
  16703. })(BABYLON.ProceduralTexture);
  16704. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  16705. })(BABYLON || (BABYLON = {}));
  16706. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  16707. var BABYLON;
  16708. (function (BABYLON) {
  16709. var EffectFallbacks = (function () {
  16710. function EffectFallbacks() {
  16711. this._defines = {};
  16712. this._currentRank = 32;
  16713. this._maxRank = -1;
  16714. }
  16715. EffectFallbacks.prototype.addFallback = function (rank, define) {
  16716. if (!this._defines[rank]) {
  16717. if (rank < this._currentRank) {
  16718. this._currentRank = rank;
  16719. }
  16720. if (rank > this._maxRank) {
  16721. this._maxRank = rank;
  16722. }
  16723. this._defines[rank] = new Array();
  16724. }
  16725. this._defines[rank].push(define);
  16726. };
  16727. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  16728. get: function () {
  16729. return this._currentRank <= this._maxRank;
  16730. },
  16731. enumerable: true,
  16732. configurable: true
  16733. });
  16734. EffectFallbacks.prototype.reduce = function (currentDefines) {
  16735. var currentFallbacks = this._defines[this._currentRank];
  16736. for (var index = 0; index < currentFallbacks.length; index++) {
  16737. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  16738. }
  16739. this._currentRank++;
  16740. return currentDefines;
  16741. };
  16742. return EffectFallbacks;
  16743. })();
  16744. BABYLON.EffectFallbacks = EffectFallbacks;
  16745. var Effect = (function () {
  16746. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  16747. var _this = this;
  16748. this._isReady = false;
  16749. this._compilationError = "";
  16750. this._valueCache = [];
  16751. this._engine = engine;
  16752. this.name = baseName;
  16753. this.defines = defines;
  16754. this._uniformsNames = uniformsNames.concat(samplers);
  16755. this._samplers = samplers;
  16756. this._attributesNames = attributesNames;
  16757. this.onError = onError;
  16758. this.onCompiled = onCompiled;
  16759. var vertexSource;
  16760. var fragmentSource;
  16761. if (baseName.vertexElement) {
  16762. vertexSource = document.getElementById(baseName.vertexElement);
  16763. if (!vertexSource) {
  16764. vertexSource = baseName.vertexElement;
  16765. }
  16766. }
  16767. else {
  16768. vertexSource = baseName.vertex || baseName;
  16769. }
  16770. if (baseName.fragmentElement) {
  16771. fragmentSource = document.getElementById(baseName.fragmentElement);
  16772. if (!fragmentSource) {
  16773. fragmentSource = baseName.fragmentElement;
  16774. }
  16775. }
  16776. else {
  16777. fragmentSource = baseName.fragment || baseName;
  16778. }
  16779. this._loadVertexShader(vertexSource, function (vertexCode) {
  16780. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  16781. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  16782. });
  16783. });
  16784. }
  16785. // Properties
  16786. Effect.prototype.isReady = function () {
  16787. return this._isReady;
  16788. };
  16789. Effect.prototype.getProgram = function () {
  16790. return this._program;
  16791. };
  16792. Effect.prototype.getAttributesNames = function () {
  16793. return this._attributesNames;
  16794. };
  16795. Effect.prototype.getAttributeLocation = function (index) {
  16796. return this._attributes[index];
  16797. };
  16798. Effect.prototype.getAttributeLocationByName = function (name) {
  16799. var index = this._attributesNames.indexOf(name);
  16800. return this._attributes[index];
  16801. };
  16802. Effect.prototype.getAttributesCount = function () {
  16803. return this._attributes.length;
  16804. };
  16805. Effect.prototype.getUniformIndex = function (uniformName) {
  16806. return this._uniformsNames.indexOf(uniformName);
  16807. };
  16808. Effect.prototype.getUniform = function (uniformName) {
  16809. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  16810. };
  16811. Effect.prototype.getSamplers = function () {
  16812. return this._samplers;
  16813. };
  16814. Effect.prototype.getCompilationError = function () {
  16815. return this._compilationError;
  16816. };
  16817. // Methods
  16818. Effect.prototype._loadVertexShader = function (vertex, callback) {
  16819. // DOM element ?
  16820. if (vertex instanceof HTMLElement) {
  16821. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  16822. callback(vertexCode);
  16823. return;
  16824. }
  16825. // Is in local store ?
  16826. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  16827. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  16828. return;
  16829. }
  16830. var vertexShaderUrl;
  16831. if (vertex[0] === ".") {
  16832. vertexShaderUrl = vertex;
  16833. }
  16834. else {
  16835. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  16836. }
  16837. // Vertex shader
  16838. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  16839. };
  16840. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  16841. // DOM element ?
  16842. if (fragment instanceof HTMLElement) {
  16843. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  16844. callback(fragmentCode);
  16845. return;
  16846. }
  16847. // Is in local store ?
  16848. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  16849. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  16850. return;
  16851. }
  16852. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  16853. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  16854. return;
  16855. }
  16856. var fragmentShaderUrl;
  16857. if (fragment[0] === ".") {
  16858. fragmentShaderUrl = fragment;
  16859. }
  16860. else {
  16861. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  16862. }
  16863. // Fragment shader
  16864. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  16865. };
  16866. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  16867. try {
  16868. var engine = this._engine;
  16869. if (!engine.getCaps().highPrecisionShaderSupported) {
  16870. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  16871. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  16872. }
  16873. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  16874. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  16875. this._attributes = engine.getAttributes(this._program, attributesNames);
  16876. for (var index = 0; index < this._samplers.length; index++) {
  16877. var sampler = this.getUniform(this._samplers[index]);
  16878. if (sampler == null) {
  16879. this._samplers.splice(index, 1);
  16880. index--;
  16881. }
  16882. }
  16883. engine.bindSamplers(this);
  16884. this._isReady = true;
  16885. if (this.onCompiled) {
  16886. this.onCompiled(this);
  16887. }
  16888. }
  16889. catch (e) {
  16890. // Is it a problem with precision?
  16891. if (e.message.indexOf("highp") !== -1) {
  16892. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  16893. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  16894. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  16895. return;
  16896. }
  16897. // Let's go through fallbacks then
  16898. if (fallbacks && fallbacks.isMoreFallbacks) {
  16899. defines = fallbacks.reduce(defines);
  16900. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  16901. }
  16902. else {
  16903. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  16904. BABYLON.Tools.Error("Defines: " + defines);
  16905. BABYLON.Tools.Error("Error: " + e.message);
  16906. this._compilationError = e.message;
  16907. if (this.onError) {
  16908. this.onError(this, this._compilationError);
  16909. }
  16910. }
  16911. }
  16912. };
  16913. Effect.prototype._bindTexture = function (channel, texture) {
  16914. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  16915. };
  16916. Effect.prototype.setTexture = function (channel, texture) {
  16917. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  16918. };
  16919. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16920. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  16921. };
  16922. //public _cacheMatrix(uniformName, matrix) {
  16923. // if (!this._valueCache[uniformName]) {
  16924. // this._valueCache[uniformName] = new BABYLON.Matrix();
  16925. // }
  16926. // for (var index = 0; index < 16; index++) {
  16927. // this._valueCache[uniformName].m[index] = matrix.m[index];
  16928. // }
  16929. //};
  16930. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  16931. if (!this._valueCache[uniformName]) {
  16932. this._valueCache[uniformName] = [x, y];
  16933. return;
  16934. }
  16935. this._valueCache[uniformName][0] = x;
  16936. this._valueCache[uniformName][1] = y;
  16937. };
  16938. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  16939. if (!this._valueCache[uniformName]) {
  16940. this._valueCache[uniformName] = [x, y, z];
  16941. return;
  16942. }
  16943. this._valueCache[uniformName][0] = x;
  16944. this._valueCache[uniformName][1] = y;
  16945. this._valueCache[uniformName][2] = z;
  16946. };
  16947. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  16948. if (!this._valueCache[uniformName]) {
  16949. this._valueCache[uniformName] = [x, y, z, w];
  16950. return;
  16951. }
  16952. this._valueCache[uniformName][0] = x;
  16953. this._valueCache[uniformName][1] = y;
  16954. this._valueCache[uniformName][2] = z;
  16955. this._valueCache[uniformName][3] = w;
  16956. };
  16957. Effect.prototype.setArray = function (uniformName, array) {
  16958. this._engine.setArray(this.getUniform(uniformName), array);
  16959. return this;
  16960. };
  16961. Effect.prototype.setArray2 = function (uniformName, array) {
  16962. this._engine.setArray2(this.getUniform(uniformName), array);
  16963. return this;
  16964. };
  16965. Effect.prototype.setArray3 = function (uniformName, array) {
  16966. this._engine.setArray3(this.getUniform(uniformName), array);
  16967. return this;
  16968. };
  16969. Effect.prototype.setArray4 = function (uniformName, array) {
  16970. this._engine.setArray4(this.getUniform(uniformName), array);
  16971. return this;
  16972. };
  16973. Effect.prototype.setMatrices = function (uniformName, matrices) {
  16974. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  16975. return this;
  16976. };
  16977. Effect.prototype.setMatrix = function (uniformName, matrix) {
  16978. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  16979. // return;
  16980. //this._cacheMatrix(uniformName, matrix);
  16981. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  16982. return this;
  16983. };
  16984. Effect.prototype.setFloat = function (uniformName, value) {
  16985. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  16986. return this;
  16987. this._valueCache[uniformName] = value;
  16988. this._engine.setFloat(this.getUniform(uniformName), value);
  16989. return this;
  16990. };
  16991. Effect.prototype.setBool = function (uniformName, bool) {
  16992. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  16993. return this;
  16994. this._valueCache[uniformName] = bool;
  16995. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  16996. return this;
  16997. };
  16998. Effect.prototype.setVector2 = function (uniformName, vector2) {
  16999. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17000. return this;
  17001. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17002. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17003. return this;
  17004. };
  17005. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17006. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17007. return this;
  17008. this._cacheFloat2(uniformName, x, y);
  17009. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17010. return this;
  17011. };
  17012. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17013. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17014. return this;
  17015. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17016. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17017. return this;
  17018. };
  17019. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17020. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17021. return this;
  17022. this._cacheFloat3(uniformName, x, y, z);
  17023. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17024. return this;
  17025. };
  17026. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17027. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17028. return this;
  17029. this._cacheFloat4(uniformName, x, y, z, w);
  17030. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17031. return this;
  17032. };
  17033. Effect.prototype.setColor3 = function (uniformName, color3) {
  17034. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  17035. return this;
  17036. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  17037. this._engine.setColor3(this.getUniform(uniformName), color3);
  17038. return this;
  17039. };
  17040. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  17041. 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)
  17042. return this;
  17043. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  17044. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  17045. return this;
  17046. };
  17047. // Statics
  17048. Effect.ShadersStore = {};
  17049. return Effect;
  17050. })();
  17051. BABYLON.Effect = Effect;
  17052. })(BABYLON || (BABYLON = {}));
  17053. //# sourceMappingURL=babylon.effect.js.map
  17054. var BABYLON;
  17055. (function (BABYLON) {
  17056. var Material = (function () {
  17057. function Material(name, scene, doNotAdd) {
  17058. this.name = name;
  17059. this.checkReadyOnEveryCall = true;
  17060. this.checkReadyOnlyOnce = false;
  17061. this.state = "";
  17062. this.alpha = 1.0;
  17063. this.backFaceCulling = true;
  17064. this._wasPreviouslyReady = false;
  17065. this._fillMode = Material.TriangleFillMode;
  17066. this.pointSize = 1.0;
  17067. this.zOffset = 0;
  17068. this.id = name;
  17069. this._scene = scene;
  17070. if (!doNotAdd) {
  17071. scene.materials.push(this);
  17072. }
  17073. }
  17074. Object.defineProperty(Material, "TriangleFillMode", {
  17075. get: function () {
  17076. return Material._TriangleFillMode;
  17077. },
  17078. enumerable: true,
  17079. configurable: true
  17080. });
  17081. Object.defineProperty(Material, "WireFrameFillMode", {
  17082. get: function () {
  17083. return Material._WireFrameFillMode;
  17084. },
  17085. enumerable: true,
  17086. configurable: true
  17087. });
  17088. Object.defineProperty(Material, "PointFillMode", {
  17089. get: function () {
  17090. return Material._PointFillMode;
  17091. },
  17092. enumerable: true,
  17093. configurable: true
  17094. });
  17095. Object.defineProperty(Material.prototype, "wireframe", {
  17096. get: function () {
  17097. return this._fillMode === Material.WireFrameFillMode;
  17098. },
  17099. set: function (value) {
  17100. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  17101. },
  17102. enumerable: true,
  17103. configurable: true
  17104. });
  17105. Object.defineProperty(Material.prototype, "pointsCloud", {
  17106. get: function () {
  17107. return this._fillMode === Material.PointFillMode;
  17108. },
  17109. set: function (value) {
  17110. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  17111. },
  17112. enumerable: true,
  17113. configurable: true
  17114. });
  17115. Object.defineProperty(Material.prototype, "fillMode", {
  17116. get: function () {
  17117. return this._fillMode;
  17118. },
  17119. set: function (value) {
  17120. this._fillMode = value;
  17121. },
  17122. enumerable: true,
  17123. configurable: true
  17124. });
  17125. Material.prototype.isReady = function (mesh, useInstances) {
  17126. return true;
  17127. };
  17128. Material.prototype.getEffect = function () {
  17129. return this._effect;
  17130. };
  17131. Material.prototype.getScene = function () {
  17132. return this._scene;
  17133. };
  17134. Material.prototype.needAlphaBlending = function () {
  17135. return (this.alpha < 1.0);
  17136. };
  17137. Material.prototype.needAlphaTesting = function () {
  17138. return false;
  17139. };
  17140. Material.prototype.getAlphaTestTexture = function () {
  17141. return null;
  17142. };
  17143. Material.prototype.trackCreation = function (onCompiled, onError) {
  17144. };
  17145. Material.prototype._preBind = function () {
  17146. var engine = this._scene.getEngine();
  17147. engine.enableEffect(this._effect);
  17148. engine.setState(this.backFaceCulling, this.zOffset);
  17149. };
  17150. Material.prototype.bind = function (world, mesh) {
  17151. this._scene._cachedMaterial = this;
  17152. if (this.onBind) {
  17153. this.onBind(this, mesh);
  17154. }
  17155. };
  17156. Material.prototype.bindOnlyWorldMatrix = function (world) {
  17157. };
  17158. Material.prototype.unbind = function () {
  17159. };
  17160. Material.prototype.dispose = function (forceDisposeEffect) {
  17161. // Remove from scene
  17162. var index = this._scene.materials.indexOf(this);
  17163. this._scene.materials.splice(index, 1);
  17164. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  17165. if (forceDisposeEffect && this._effect) {
  17166. this._scene.getEngine()._releaseEffect(this._effect);
  17167. this._effect = null;
  17168. }
  17169. // Callback
  17170. if (this.onDispose) {
  17171. this.onDispose();
  17172. }
  17173. };
  17174. Material._TriangleFillMode = 0;
  17175. Material._WireFrameFillMode = 1;
  17176. Material._PointFillMode = 2;
  17177. return Material;
  17178. })();
  17179. BABYLON.Material = Material;
  17180. })(BABYLON || (BABYLON = {}));
  17181. //# sourceMappingURL=babylon.material.js.map
  17182. var __extends = this.__extends || function (d, b) {
  17183. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17184. function __() { this.constructor = d; }
  17185. __.prototype = b.prototype;
  17186. d.prototype = new __();
  17187. };
  17188. var BABYLON;
  17189. (function (BABYLON) {
  17190. var maxSimultaneousLights = 4;
  17191. var FresnelParameters = (function () {
  17192. function FresnelParameters() {
  17193. this.isEnabled = true;
  17194. this.leftColor = BABYLON.Color3.White();
  17195. this.rightColor = BABYLON.Color3.Black();
  17196. this.bias = 0;
  17197. this.power = 1;
  17198. }
  17199. return FresnelParameters;
  17200. })();
  17201. BABYLON.FresnelParameters = FresnelParameters;
  17202. var StandardMaterial = (function (_super) {
  17203. __extends(StandardMaterial, _super);
  17204. function StandardMaterial(name, scene) {
  17205. var _this = this;
  17206. _super.call(this, name, scene);
  17207. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17208. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  17209. this.specularColor = new BABYLON.Color3(1, 1, 1);
  17210. this.specularPower = 64;
  17211. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  17212. this.useAlphaFromDiffuseTexture = false;
  17213. this.useSpecularOverAlpha = true;
  17214. this.fogEnabled = true;
  17215. this._cachedDefines = null;
  17216. this._renderTargets = new BABYLON.SmartArray(16);
  17217. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  17218. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  17219. this._scaledDiffuse = new BABYLON.Color3();
  17220. this._scaledSpecular = new BABYLON.Color3();
  17221. this.getRenderTargetTextures = function () {
  17222. _this._renderTargets.reset();
  17223. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  17224. _this._renderTargets.push(_this.reflectionTexture);
  17225. }
  17226. return _this._renderTargets;
  17227. };
  17228. }
  17229. StandardMaterial.prototype.needAlphaBlending = function () {
  17230. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  17231. };
  17232. StandardMaterial.prototype.needAlphaTesting = function () {
  17233. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  17234. };
  17235. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  17236. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  17237. };
  17238. StandardMaterial.prototype.getAlphaTestTexture = function () {
  17239. return this.diffuseTexture;
  17240. };
  17241. // Methods
  17242. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  17243. if (this.checkReadyOnlyOnce) {
  17244. if (this._wasPreviouslyReady) {
  17245. return true;
  17246. }
  17247. }
  17248. var scene = this.getScene();
  17249. if (!this.checkReadyOnEveryCall) {
  17250. if (this._renderId === scene.getRenderId()) {
  17251. return true;
  17252. }
  17253. }
  17254. var engine = scene.getEngine();
  17255. var defines = [];
  17256. var fallbacks = new BABYLON.EffectFallbacks();
  17257. var needNormals = false;
  17258. var needUVs = false;
  17259. // Textures
  17260. if (scene.texturesEnabled) {
  17261. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  17262. if (!this.diffuseTexture.isReady()) {
  17263. return false;
  17264. }
  17265. else {
  17266. needUVs = true;
  17267. defines.push("#define DIFFUSE");
  17268. }
  17269. }
  17270. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  17271. if (!this.ambientTexture.isReady()) {
  17272. return false;
  17273. }
  17274. else {
  17275. needUVs = true;
  17276. defines.push("#define AMBIENT");
  17277. }
  17278. }
  17279. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  17280. if (!this.opacityTexture.isReady()) {
  17281. return false;
  17282. }
  17283. else {
  17284. needUVs = true;
  17285. defines.push("#define OPACITY");
  17286. if (this.opacityTexture.getAlphaFromRGB) {
  17287. defines.push("#define OPACITYRGB");
  17288. }
  17289. }
  17290. }
  17291. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  17292. if (!this.reflectionTexture.isReady()) {
  17293. return false;
  17294. }
  17295. else {
  17296. needNormals = true;
  17297. needUVs = true;
  17298. defines.push("#define REFLECTION");
  17299. fallbacks.addFallback(0, "REFLECTION");
  17300. }
  17301. }
  17302. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  17303. if (!this.emissiveTexture.isReady()) {
  17304. return false;
  17305. }
  17306. else {
  17307. needUVs = true;
  17308. defines.push("#define EMISSIVE");
  17309. }
  17310. }
  17311. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  17312. if (!this.specularTexture.isReady()) {
  17313. return false;
  17314. }
  17315. else {
  17316. needUVs = true;
  17317. defines.push("#define SPECULAR");
  17318. fallbacks.addFallback(0, "SPECULAR");
  17319. }
  17320. }
  17321. }
  17322. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  17323. if (!this.bumpTexture.isReady()) {
  17324. return false;
  17325. }
  17326. else {
  17327. needUVs = true;
  17328. defines.push("#define BUMP");
  17329. fallbacks.addFallback(0, "BUMP");
  17330. }
  17331. }
  17332. // Effect
  17333. if (this.useSpecularOverAlpha) {
  17334. defines.push("#define SPECULAROVERALPHA");
  17335. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  17336. }
  17337. if (scene.clipPlane) {
  17338. defines.push("#define CLIPPLANE");
  17339. }
  17340. if (engine.getAlphaTesting()) {
  17341. defines.push("#define ALPHATEST");
  17342. }
  17343. if (this._shouldUseAlphaFromDiffuseTexture()) {
  17344. defines.push("#define ALPHAFROMDIFFUSE");
  17345. }
  17346. // Point size
  17347. if (this.pointsCloud || scene.forcePointsCloud) {
  17348. defines.push("#define POINTSIZE");
  17349. }
  17350. // Fog
  17351. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  17352. defines.push("#define FOG");
  17353. fallbacks.addFallback(1, "FOG");
  17354. }
  17355. var shadowsActivated = false;
  17356. var lightIndex = 0;
  17357. if (scene.lightsEnabled) {
  17358. for (var index = 0; index < scene.lights.length; index++) {
  17359. var light = scene.lights[index];
  17360. if (!light.isEnabled()) {
  17361. continue;
  17362. }
  17363. // Excluded check
  17364. if (light._excludedMeshesIds.length > 0) {
  17365. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  17366. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  17367. if (excludedMesh) {
  17368. light.excludedMeshes.push(excludedMesh);
  17369. }
  17370. }
  17371. light._excludedMeshesIds = [];
  17372. }
  17373. // Included check
  17374. if (light._includedOnlyMeshesIds.length > 0) {
  17375. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  17376. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  17377. if (includedOnlyMesh) {
  17378. light.includedOnlyMeshes.push(includedOnlyMesh);
  17379. }
  17380. }
  17381. light._includedOnlyMeshesIds = [];
  17382. }
  17383. if (!light.canAffectMesh(mesh)) {
  17384. continue;
  17385. }
  17386. needNormals = true;
  17387. defines.push("#define LIGHT" + lightIndex);
  17388. if (lightIndex > 0) {
  17389. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  17390. }
  17391. var type;
  17392. if (light instanceof BABYLON.SpotLight) {
  17393. type = "#define SPOTLIGHT" + lightIndex;
  17394. }
  17395. else if (light instanceof BABYLON.HemisphericLight) {
  17396. type = "#define HEMILIGHT" + lightIndex;
  17397. }
  17398. else {
  17399. type = "#define POINTDIRLIGHT" + lightIndex;
  17400. }
  17401. defines.push(type);
  17402. if (lightIndex > 0) {
  17403. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  17404. }
  17405. // Shadows
  17406. if (scene.shadowsEnabled) {
  17407. var shadowGenerator = light.getShadowGenerator();
  17408. if (mesh && mesh.receiveShadows && shadowGenerator) {
  17409. defines.push("#define SHADOW" + lightIndex);
  17410. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  17411. if (!shadowsActivated) {
  17412. defines.push("#define SHADOWS");
  17413. shadowsActivated = true;
  17414. }
  17415. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  17416. defines.push("#define SHADOWVSM" + lightIndex);
  17417. if (lightIndex > 0) {
  17418. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  17419. }
  17420. }
  17421. if (shadowGenerator.usePoissonSampling) {
  17422. defines.push("#define SHADOWPCF" + lightIndex);
  17423. if (lightIndex > 0) {
  17424. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  17425. }
  17426. }
  17427. }
  17428. }
  17429. lightIndex++;
  17430. if (lightIndex === maxSimultaneousLights)
  17431. break;
  17432. }
  17433. }
  17434. if (StandardMaterial.FresnelEnabled) {
  17435. // Fresnel
  17436. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17437. var fresnelRank = 1;
  17438. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  17439. defines.push("#define DIFFUSEFRESNEL");
  17440. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  17441. fresnelRank++;
  17442. }
  17443. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  17444. defines.push("#define OPACITYFRESNEL");
  17445. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  17446. fresnelRank++;
  17447. }
  17448. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17449. defines.push("#define REFLECTIONFRESNEL");
  17450. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  17451. fresnelRank++;
  17452. }
  17453. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  17454. defines.push("#define EMISSIVEFRESNEL");
  17455. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  17456. fresnelRank++;
  17457. }
  17458. needNormals = true;
  17459. defines.push("#define FRESNEL");
  17460. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  17461. }
  17462. }
  17463. // Attribs
  17464. var attribs = [BABYLON.VertexBuffer.PositionKind];
  17465. if (mesh) {
  17466. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17467. attribs.push(BABYLON.VertexBuffer.NormalKind);
  17468. defines.push("#define NORMAL");
  17469. }
  17470. if (needUVs) {
  17471. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17472. attribs.push(BABYLON.VertexBuffer.UVKind);
  17473. defines.push("#define UV1");
  17474. }
  17475. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17476. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  17477. defines.push("#define UV2");
  17478. }
  17479. }
  17480. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17481. attribs.push(BABYLON.VertexBuffer.ColorKind);
  17482. defines.push("#define VERTEXCOLOR");
  17483. if (mesh.hasVertexAlpha) {
  17484. defines.push("#define VERTEXALPHA");
  17485. }
  17486. }
  17487. if (mesh.useBones) {
  17488. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17489. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17490. defines.push("#define BONES");
  17491. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  17492. defines.push("#define BONES4");
  17493. fallbacks.addFallback(0, "BONES4");
  17494. }
  17495. // Instances
  17496. if (useInstances) {
  17497. defines.push("#define INSTANCES");
  17498. attribs.push("world0");
  17499. attribs.push("world1");
  17500. attribs.push("world2");
  17501. attribs.push("world3");
  17502. }
  17503. }
  17504. // Get correct effect
  17505. var join = defines.join("\n");
  17506. if (this._cachedDefines !== join) {
  17507. this._cachedDefines = join;
  17508. scene.resetCachedMaterial();
  17509. // Legacy browser patch
  17510. var shaderName = "default";
  17511. if (!scene.getEngine().getCaps().standardDerivatives) {
  17512. shaderName = "legacydefault";
  17513. }
  17514. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  17515. }
  17516. if (!this._effect.isReady()) {
  17517. return false;
  17518. }
  17519. this._renderId = scene.getRenderId();
  17520. this._wasPreviouslyReady = true;
  17521. return true;
  17522. };
  17523. StandardMaterial.prototype.unbind = function () {
  17524. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  17525. this._effect.setTexture("reflection2DSampler", null);
  17526. }
  17527. };
  17528. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  17529. this._effect.setMatrix("world", world);
  17530. };
  17531. StandardMaterial.prototype.bind = function (world, mesh) {
  17532. var scene = this.getScene();
  17533. // Matrices
  17534. this.bindOnlyWorldMatrix(world);
  17535. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  17536. // Bones
  17537. if (mesh && mesh.useBones) {
  17538. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  17539. }
  17540. if (scene.getCachedMaterial() !== this) {
  17541. if (StandardMaterial.FresnelEnabled) {
  17542. // Fresnel
  17543. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  17544. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  17545. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  17546. }
  17547. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  17548. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  17549. }
  17550. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  17551. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  17552. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  17553. }
  17554. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  17555. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  17556. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  17557. }
  17558. }
  17559. // Textures
  17560. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  17561. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  17562. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  17563. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  17564. }
  17565. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  17566. this._effect.setTexture("ambientSampler", this.ambientTexture);
  17567. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  17568. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  17569. }
  17570. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  17571. this._effect.setTexture("opacitySampler", this.opacityTexture);
  17572. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  17573. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  17574. }
  17575. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  17576. if (this.reflectionTexture.isCube) {
  17577. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  17578. }
  17579. else {
  17580. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  17581. }
  17582. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  17583. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  17584. }
  17585. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  17586. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  17587. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  17588. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  17589. }
  17590. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  17591. this._effect.setTexture("specularSampler", this.specularTexture);
  17592. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  17593. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  17594. }
  17595. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  17596. this._effect.setTexture("bumpSampler", this.bumpTexture);
  17597. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  17598. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  17599. }
  17600. // Clip plane
  17601. if (scene.clipPlane) {
  17602. var clipPlane = scene.clipPlane;
  17603. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  17604. }
  17605. // Point size
  17606. if (this.pointsCloud) {
  17607. this._effect.setFloat("pointSize", this.pointSize);
  17608. }
  17609. // Colors
  17610. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  17611. // Scaling down color according to emissive
  17612. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  17613. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  17614. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  17615. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  17616. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  17617. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  17618. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  17619. }
  17620. // Scaling down color according to emissive
  17621. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  17622. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  17623. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  17624. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  17625. if (scene.lightsEnabled) {
  17626. var lightIndex = 0;
  17627. for (var index = 0; index < scene.lights.length; index++) {
  17628. var light = scene.lights[index];
  17629. if (!light.isEnabled()) {
  17630. continue;
  17631. }
  17632. if (!light.canAffectMesh(mesh)) {
  17633. continue;
  17634. }
  17635. if (light instanceof BABYLON.PointLight) {
  17636. // Point Light
  17637. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  17638. }
  17639. else if (light instanceof BABYLON.DirectionalLight) {
  17640. // Directional Light
  17641. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  17642. }
  17643. else if (light instanceof BABYLON.SpotLight) {
  17644. // Spot Light
  17645. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  17646. }
  17647. else if (light instanceof BABYLON.HemisphericLight) {
  17648. // Hemispheric Light
  17649. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  17650. }
  17651. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  17652. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  17653. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  17654. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  17655. // Shadows
  17656. if (scene.shadowsEnabled) {
  17657. var shadowGenerator = light.getShadowGenerator();
  17658. if (mesh.receiveShadows && shadowGenerator) {
  17659. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  17660. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  17661. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  17662. }
  17663. }
  17664. lightIndex++;
  17665. if (lightIndex === maxSimultaneousLights)
  17666. break;
  17667. }
  17668. }
  17669. // View
  17670. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  17671. this._effect.setMatrix("view", scene.getViewMatrix());
  17672. }
  17673. // Fog
  17674. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  17675. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  17676. this._effect.setColor3("vFogColor", scene.fogColor);
  17677. }
  17678. _super.prototype.bind.call(this, world, mesh);
  17679. };
  17680. StandardMaterial.prototype.getAnimatables = function () {
  17681. var results = [];
  17682. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  17683. results.push(this.diffuseTexture);
  17684. }
  17685. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  17686. results.push(this.ambientTexture);
  17687. }
  17688. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  17689. results.push(this.opacityTexture);
  17690. }
  17691. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  17692. results.push(this.reflectionTexture);
  17693. }
  17694. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  17695. results.push(this.emissiveTexture);
  17696. }
  17697. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  17698. results.push(this.specularTexture);
  17699. }
  17700. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  17701. results.push(this.bumpTexture);
  17702. }
  17703. return results;
  17704. };
  17705. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  17706. if (this.diffuseTexture) {
  17707. this.diffuseTexture.dispose();
  17708. }
  17709. if (this.ambientTexture) {
  17710. this.ambientTexture.dispose();
  17711. }
  17712. if (this.opacityTexture) {
  17713. this.opacityTexture.dispose();
  17714. }
  17715. if (this.reflectionTexture) {
  17716. this.reflectionTexture.dispose();
  17717. }
  17718. if (this.emissiveTexture) {
  17719. this.emissiveTexture.dispose();
  17720. }
  17721. if (this.specularTexture) {
  17722. this.specularTexture.dispose();
  17723. }
  17724. if (this.bumpTexture) {
  17725. this.bumpTexture.dispose();
  17726. }
  17727. _super.prototype.dispose.call(this, forceDisposeEffect);
  17728. };
  17729. StandardMaterial.prototype.clone = function (name) {
  17730. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  17731. // Base material
  17732. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  17733. newStandardMaterial.alpha = this.alpha;
  17734. newStandardMaterial.fillMode = this.fillMode;
  17735. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  17736. // Standard material
  17737. if (this.diffuseTexture && this.diffuseTexture.clone) {
  17738. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  17739. }
  17740. if (this.ambientTexture && this.ambientTexture.clone) {
  17741. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  17742. }
  17743. if (this.opacityTexture && this.opacityTexture.clone) {
  17744. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  17745. }
  17746. if (this.reflectionTexture && this.reflectionTexture.clone) {
  17747. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  17748. }
  17749. if (this.emissiveTexture && this.emissiveTexture.clone) {
  17750. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  17751. }
  17752. if (this.specularTexture && this.specularTexture.clone) {
  17753. newStandardMaterial.specularTexture = this.specularTexture.clone();
  17754. }
  17755. if (this.bumpTexture && this.bumpTexture.clone) {
  17756. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  17757. }
  17758. newStandardMaterial.ambientColor = this.ambientColor.clone();
  17759. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  17760. newStandardMaterial.specularColor = this.specularColor.clone();
  17761. newStandardMaterial.specularPower = this.specularPower;
  17762. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  17763. return newStandardMaterial;
  17764. };
  17765. // Statics
  17766. // Flags used to enable or disable a type of texture for all Standard Materials
  17767. StandardMaterial.DiffuseTextureEnabled = true;
  17768. StandardMaterial.AmbientTextureEnabled = true;
  17769. StandardMaterial.OpacityTextureEnabled = true;
  17770. StandardMaterial.ReflectionTextureEnabled = true;
  17771. StandardMaterial.EmissiveTextureEnabled = true;
  17772. StandardMaterial.SpecularTextureEnabled = true;
  17773. StandardMaterial.BumpTextureEnabled = true;
  17774. StandardMaterial.FresnelEnabled = true;
  17775. return StandardMaterial;
  17776. })(BABYLON.Material);
  17777. BABYLON.StandardMaterial = StandardMaterial;
  17778. })(BABYLON || (BABYLON = {}));
  17779. //# sourceMappingURL=babylon.standardMaterial.js.map
  17780. var __extends = this.__extends || function (d, b) {
  17781. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17782. function __() { this.constructor = d; }
  17783. __.prototype = b.prototype;
  17784. d.prototype = new __();
  17785. };
  17786. var BABYLON;
  17787. (function (BABYLON) {
  17788. var MultiMaterial = (function (_super) {
  17789. __extends(MultiMaterial, _super);
  17790. function MultiMaterial(name, scene) {
  17791. _super.call(this, name, scene, true);
  17792. this.subMaterials = new Array();
  17793. scene.multiMaterials.push(this);
  17794. }
  17795. // Properties
  17796. MultiMaterial.prototype.getSubMaterial = function (index) {
  17797. if (index < 0 || index >= this.subMaterials.length) {
  17798. return this.getScene().defaultMaterial;
  17799. }
  17800. return this.subMaterials[index];
  17801. };
  17802. // Methods
  17803. MultiMaterial.prototype.isReady = function (mesh) {
  17804. for (var index = 0; index < this.subMaterials.length; index++) {
  17805. var subMaterial = this.subMaterials[index];
  17806. if (subMaterial) {
  17807. if (!this.subMaterials[index].isReady(mesh)) {
  17808. return false;
  17809. }
  17810. }
  17811. }
  17812. return true;
  17813. };
  17814. MultiMaterial.prototype.clone = function (name) {
  17815. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  17816. for (var index = 0; index < this.subMaterials.length; index++) {
  17817. var subMaterial = this.subMaterials[index];
  17818. newMultiMaterial.subMaterials.push(subMaterial);
  17819. }
  17820. return newMultiMaterial;
  17821. };
  17822. return MultiMaterial;
  17823. })(BABYLON.Material);
  17824. BABYLON.MultiMaterial = MultiMaterial;
  17825. })(BABYLON || (BABYLON = {}));
  17826. //# sourceMappingURL=babylon.multiMaterial.js.map
  17827. var BABYLON;
  17828. (function (BABYLON) {
  17829. var SceneLoader = (function () {
  17830. function SceneLoader() {
  17831. }
  17832. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17833. get: function () {
  17834. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17835. },
  17836. set: function (value) {
  17837. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17838. },
  17839. enumerable: true,
  17840. configurable: true
  17841. });
  17842. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17843. get: function () {
  17844. return SceneLoader._ShowLoadingScreen;
  17845. },
  17846. set: function (value) {
  17847. SceneLoader._ShowLoadingScreen = value;
  17848. },
  17849. enumerable: true,
  17850. configurable: true
  17851. });
  17852. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17853. var dotPosition = sceneFilename.lastIndexOf(".");
  17854. var queryStringPosition = sceneFilename.indexOf("?");
  17855. if (queryStringPosition === -1) {
  17856. queryStringPosition = sceneFilename.length;
  17857. }
  17858. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17859. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17860. var plugin = this._registeredPlugins[index];
  17861. if (plugin.extensions.indexOf(extension) !== -1) {
  17862. return plugin;
  17863. }
  17864. }
  17865. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17866. };
  17867. // Public functions
  17868. SceneLoader.RegisterPlugin = function (plugin) {
  17869. plugin.extensions = plugin.extensions.toLowerCase();
  17870. SceneLoader._registeredPlugins.push(plugin);
  17871. };
  17872. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17873. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  17874. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  17875. return;
  17876. }
  17877. var manifestChecked = function (success) {
  17878. scene.database = database;
  17879. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17880. var importMeshFromData = function (data) {
  17881. var meshes = [];
  17882. var particleSystems = [];
  17883. var skeletons = [];
  17884. try {
  17885. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17886. if (onerror) {
  17887. onerror(scene, 'unable to load the scene');
  17888. }
  17889. return;
  17890. }
  17891. }
  17892. catch (e) {
  17893. if (onerror) {
  17894. onerror(scene, e);
  17895. }
  17896. return;
  17897. }
  17898. if (onsuccess) {
  17899. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17900. onsuccess(meshes, particleSystems, skeletons);
  17901. }
  17902. };
  17903. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17904. // Direct load
  17905. importMeshFromData(sceneFilename.substr(5));
  17906. return;
  17907. }
  17908. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17909. importMeshFromData(data);
  17910. }, progressCallBack, database);
  17911. };
  17912. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17913. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17914. };
  17915. /**
  17916. * Load a scene
  17917. * @param rootUrl a string that defines the root url for scene and resources
  17918. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17919. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17920. */
  17921. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17922. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17923. };
  17924. /**
  17925. * Append a scene
  17926. * @param rootUrl a string that defines the root url for scene and resources
  17927. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17928. * @param scene is the instance of BABYLON.Scene to append to
  17929. */
  17930. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17931. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  17932. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  17933. return;
  17934. }
  17935. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17936. var database;
  17937. if (SceneLoader.ShowLoadingScreen) {
  17938. scene.getEngine().displayLoadingUI();
  17939. }
  17940. var loadSceneFromData = function (data) {
  17941. scene.database = database;
  17942. if (!plugin.load(scene, data, rootUrl)) {
  17943. if (onerror) {
  17944. onerror(scene);
  17945. }
  17946. scene.getEngine().hideLoadingUI();
  17947. return;
  17948. }
  17949. if (onsuccess) {
  17950. onsuccess(scene);
  17951. }
  17952. if (SceneLoader.ShowLoadingScreen) {
  17953. scene.executeWhenReady(function () {
  17954. scene.getEngine().hideLoadingUI();
  17955. });
  17956. }
  17957. };
  17958. var manifestChecked = function (success) {
  17959. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17960. };
  17961. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17962. // Direct load
  17963. loadSceneFromData(sceneFilename.substr(5));
  17964. return;
  17965. }
  17966. if (rootUrl.indexOf("file:") === -1) {
  17967. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17968. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17969. }
  17970. else {
  17971. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17972. }
  17973. };
  17974. // Flags
  17975. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17976. SceneLoader._ShowLoadingScreen = true;
  17977. // Members
  17978. SceneLoader._registeredPlugins = new Array();
  17979. return SceneLoader;
  17980. })();
  17981. BABYLON.SceneLoader = SceneLoader;
  17982. ;
  17983. })(BABYLON || (BABYLON = {}));
  17984. //# sourceMappingURL=babylon.sceneLoader.js.map
  17985. var BABYLON;
  17986. (function (BABYLON) {
  17987. var Internals;
  17988. (function (Internals) {
  17989. var checkColors4 = function (colors, count) {
  17990. // Check if color3 was used
  17991. if (colors.length === count * 3) {
  17992. var colors4 = [];
  17993. for (var index = 0; index < colors.length; index += 3) {
  17994. var newIndex = (index / 3) * 4;
  17995. colors4[newIndex] = colors[index];
  17996. colors4[newIndex + 1] = colors[index + 1];
  17997. colors4[newIndex + 2] = colors[index + 2];
  17998. colors4[newIndex + 3] = 1.0;
  17999. }
  18000. return colors4;
  18001. }
  18002. return colors;
  18003. };
  18004. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18005. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18006. texture.name = parsedTexture.name;
  18007. texture.hasAlpha = parsedTexture.hasAlpha;
  18008. texture.level = parsedTexture.level;
  18009. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18010. return texture;
  18011. };
  18012. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18013. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18014. return null;
  18015. }
  18016. if (parsedTexture.isCube) {
  18017. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18018. }
  18019. var texture;
  18020. if (parsedTexture.mirrorPlane) {
  18021. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18022. texture._waitingRenderList = parsedTexture.renderList;
  18023. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18024. }
  18025. else if (parsedTexture.isRenderTarget) {
  18026. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18027. texture._waitingRenderList = parsedTexture.renderList;
  18028. }
  18029. else {
  18030. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18031. }
  18032. texture.name = parsedTexture.name;
  18033. texture.hasAlpha = parsedTexture.hasAlpha;
  18034. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18035. texture.level = parsedTexture.level;
  18036. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18037. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18038. texture.uOffset = parsedTexture.uOffset;
  18039. texture.vOffset = parsedTexture.vOffset;
  18040. texture.uScale = parsedTexture.uScale;
  18041. texture.vScale = parsedTexture.vScale;
  18042. texture.uAng = parsedTexture.uAng;
  18043. texture.vAng = parsedTexture.vAng;
  18044. texture.wAng = parsedTexture.wAng;
  18045. texture.wrapU = parsedTexture.wrapU;
  18046. texture.wrapV = parsedTexture.wrapV;
  18047. // Animations
  18048. if (parsedTexture.animations) {
  18049. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18050. var parsedAnimation = parsedTexture.animations[animationIndex];
  18051. texture.animations.push(parseAnimation(parsedAnimation));
  18052. }
  18053. }
  18054. return texture;
  18055. };
  18056. var parseSkeleton = function (parsedSkeleton, scene) {
  18057. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18058. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18059. var parsedBone = parsedSkeleton.bones[index];
  18060. var parentBone = null;
  18061. if (parsedBone.parentBoneIndex > -1) {
  18062. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18063. }
  18064. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18065. if (parsedBone.animation) {
  18066. bone.animations.push(parseAnimation(parsedBone.animation));
  18067. }
  18068. }
  18069. return skeleton;
  18070. };
  18071. var parseFresnelParameters = function (parsedFresnelParameters) {
  18072. var fresnelParameters = new BABYLON.FresnelParameters();
  18073. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18074. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18075. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18076. fresnelParameters.bias = parsedFresnelParameters.bias;
  18077. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18078. return fresnelParameters;
  18079. };
  18080. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18081. var material;
  18082. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18083. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18084. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18085. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18086. material.specularPower = parsedMaterial.specularPower;
  18087. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18088. material.alpha = parsedMaterial.alpha;
  18089. material.id = parsedMaterial.id;
  18090. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18091. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18092. material.wireframe = parsedMaterial.wireframe;
  18093. if (parsedMaterial.diffuseTexture) {
  18094. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18095. }
  18096. if (parsedMaterial.diffuseFresnelParameters) {
  18097. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18098. }
  18099. if (parsedMaterial.ambientTexture) {
  18100. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18101. }
  18102. if (parsedMaterial.opacityTexture) {
  18103. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18104. }
  18105. if (parsedMaterial.opacityFresnelParameters) {
  18106. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18107. }
  18108. if (parsedMaterial.reflectionTexture) {
  18109. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18110. }
  18111. if (parsedMaterial.reflectionFresnelParameters) {
  18112. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18113. }
  18114. if (parsedMaterial.emissiveTexture) {
  18115. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18116. }
  18117. if (parsedMaterial.emissiveFresnelParameters) {
  18118. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18119. }
  18120. if (parsedMaterial.specularTexture) {
  18121. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18122. }
  18123. if (parsedMaterial.bumpTexture) {
  18124. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18125. }
  18126. return material;
  18127. };
  18128. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18129. for (var index = 0; index < parsedData.materials.length; index++) {
  18130. var parsedMaterial = parsedData.materials[index];
  18131. if (parsedMaterial.id === id) {
  18132. return parseMaterial(parsedMaterial, scene, rootUrl);
  18133. }
  18134. }
  18135. return null;
  18136. };
  18137. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18138. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18139. multiMaterial.id = parsedMultiMaterial.id;
  18140. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18141. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18142. var subMatId = parsedMultiMaterial.materials[matIndex];
  18143. if (subMatId) {
  18144. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18145. }
  18146. else {
  18147. multiMaterial.subMaterials.push(null);
  18148. }
  18149. }
  18150. return multiMaterial;
  18151. };
  18152. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18153. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18154. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18155. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18156. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18157. var parsedFlare = parsedLensFlareSystem.flares[index];
  18158. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18159. }
  18160. return lensFlareSystem;
  18161. };
  18162. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18163. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18164. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18165. if (parsedParticleSystem.textureName) {
  18166. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18167. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18168. }
  18169. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18170. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18171. particleSystem.minSize = parsedParticleSystem.minSize;
  18172. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18173. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18174. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18175. particleSystem.emitter = emitter;
  18176. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18177. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18178. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18179. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18180. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18181. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18182. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18183. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18184. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18185. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18186. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18187. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18188. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18189. particleSystem.start();
  18190. return particleSystem;
  18191. };
  18192. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18193. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18194. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18195. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18196. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18197. shadowGenerator.getShadowMap().renderList.push(mesh);
  18198. }
  18199. if (parsedShadowGenerator.usePoissonSampling) {
  18200. shadowGenerator.usePoissonSampling = true;
  18201. }
  18202. else if (parsedShadowGenerator.useVarianceShadowMap) {
  18203. shadowGenerator.useVarianceShadowMap = true;
  18204. }
  18205. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  18206. shadowGenerator.useBlurVarianceShadowMap = true;
  18207. if (parsedShadowGenerator.blurScale) {
  18208. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  18209. }
  18210. if (parsedShadowGenerator.blurBoxOffset) {
  18211. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  18212. }
  18213. }
  18214. if (parsedShadowGenerator.bias !== undefined) {
  18215. shadowGenerator.bias = parsedShadowGenerator.bias;
  18216. }
  18217. return shadowGenerator;
  18218. };
  18219. var parseAnimation = function (parsedAnimation) {
  18220. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18221. var dataType = parsedAnimation.dataType;
  18222. var keys = [];
  18223. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18224. var key = parsedAnimation.keys[index];
  18225. var data;
  18226. switch (dataType) {
  18227. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18228. data = key.values[0];
  18229. break;
  18230. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18231. data = BABYLON.Quaternion.FromArray(key.values);
  18232. break;
  18233. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18234. data = BABYLON.Matrix.FromArray(key.values);
  18235. break;
  18236. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18237. default:
  18238. data = BABYLON.Vector3.FromArray(key.values);
  18239. break;
  18240. }
  18241. keys.push({
  18242. frame: key.frame,
  18243. value: data
  18244. });
  18245. }
  18246. animation.setKeys(keys);
  18247. return animation;
  18248. };
  18249. var parseLight = function (parsedLight, scene) {
  18250. var light;
  18251. switch (parsedLight.type) {
  18252. case 0:
  18253. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18254. break;
  18255. case 1:
  18256. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18257. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18258. break;
  18259. case 2:
  18260. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18261. break;
  18262. case 3:
  18263. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18264. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18265. break;
  18266. }
  18267. light.id = parsedLight.id;
  18268. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18269. if (parsedLight.intensity !== undefined) {
  18270. light.intensity = parsedLight.intensity;
  18271. }
  18272. if (parsedLight.range) {
  18273. light.range = parsedLight.range;
  18274. }
  18275. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18276. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18277. if (parsedLight.excludedMeshesIds) {
  18278. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18279. }
  18280. // Parent
  18281. if (parsedLight.parentId) {
  18282. light._waitingParentId = parsedLight.parentId;
  18283. }
  18284. if (parsedLight.includedOnlyMeshesIds) {
  18285. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18286. }
  18287. // Animations
  18288. if (parsedLight.animations) {
  18289. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18290. var parsedAnimation = parsedLight.animations[animationIndex];
  18291. light.animations.push(parseAnimation(parsedAnimation));
  18292. }
  18293. }
  18294. if (parsedLight.autoAnimate) {
  18295. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18296. }
  18297. };
  18298. var parseCamera = function (parsedCamera, scene) {
  18299. var camera;
  18300. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18301. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18302. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18303. var alpha = parsedCamera.alpha;
  18304. var beta = parsedCamera.beta;
  18305. var radius = parsedCamera.radius;
  18306. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18307. var eye_space = parsedCamera.eye_space;
  18308. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18309. }
  18310. else {
  18311. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18312. }
  18313. }
  18314. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18315. eye_space = parsedCamera.eye_space;
  18316. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18317. }
  18318. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18319. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18320. }
  18321. else if (parsedCamera.type === "FollowCamera") {
  18322. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18323. camera.heightOffset = parsedCamera.heightOffset;
  18324. camera.radius = parsedCamera.radius;
  18325. camera.rotationOffset = parsedCamera.rotationOffset;
  18326. if (lockedTargetMesh)
  18327. camera.target = lockedTargetMesh;
  18328. }
  18329. else if (parsedCamera.type === "GamepadCamera") {
  18330. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18331. }
  18332. else if (parsedCamera.type === "TouchCamera") {
  18333. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18334. }
  18335. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18336. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18337. }
  18338. else if (parsedCamera.type === "WebVRCamera") {
  18339. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  18340. }
  18341. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18342. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  18343. }
  18344. else {
  18345. // Free Camera is the default value
  18346. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18347. }
  18348. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18349. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18350. camera.lockedTarget = lockedTargetMesh;
  18351. }
  18352. camera.id = parsedCamera.id;
  18353. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18354. // Parent
  18355. if (parsedCamera.parentId) {
  18356. camera._waitingParentId = parsedCamera.parentId;
  18357. }
  18358. // Target
  18359. if (parsedCamera.target) {
  18360. if (camera.setTarget) {
  18361. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18362. }
  18363. else {
  18364. //For ArcRotate
  18365. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  18366. }
  18367. }
  18368. else {
  18369. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18370. }
  18371. camera.fov = parsedCamera.fov;
  18372. camera.minZ = parsedCamera.minZ;
  18373. camera.maxZ = parsedCamera.maxZ;
  18374. camera.speed = parsedCamera.speed;
  18375. camera.inertia = parsedCamera.inertia;
  18376. camera.checkCollisions = parsedCamera.checkCollisions;
  18377. camera.applyGravity = parsedCamera.applyGravity;
  18378. if (parsedCamera.ellipsoid) {
  18379. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18380. }
  18381. // Animations
  18382. if (parsedCamera.animations) {
  18383. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18384. var parsedAnimation = parsedCamera.animations[animationIndex];
  18385. camera.animations.push(parseAnimation(parsedAnimation));
  18386. }
  18387. }
  18388. if (parsedCamera.autoAnimate) {
  18389. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18390. }
  18391. // Layer Mask
  18392. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18393. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18394. }
  18395. else {
  18396. camera.layerMask = 0xFFFFFFFF;
  18397. }
  18398. return camera;
  18399. };
  18400. var parseGeometry = function (parsedGeometry, scene) {
  18401. var id = parsedGeometry.id;
  18402. return scene.getGeometryByID(id);
  18403. };
  18404. var parseBox = function (parsedBox, scene) {
  18405. if (parseGeometry(parsedBox, scene)) {
  18406. return null; // null since geometry could be something else than a box...
  18407. }
  18408. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18409. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18410. scene.pushGeometry(box, true);
  18411. return box;
  18412. };
  18413. var parseSphere = function (parsedSphere, scene) {
  18414. if (parseGeometry(parsedSphere, scene)) {
  18415. return null; // null since geometry could be something else than a sphere...
  18416. }
  18417. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18418. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18419. scene.pushGeometry(sphere, true);
  18420. return sphere;
  18421. };
  18422. var parseCylinder = function (parsedCylinder, scene) {
  18423. if (parseGeometry(parsedCylinder, scene)) {
  18424. return null; // null since geometry could be something else than a cylinder...
  18425. }
  18426. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18427. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18428. scene.pushGeometry(cylinder, true);
  18429. return cylinder;
  18430. };
  18431. var parseTorus = function (parsedTorus, scene) {
  18432. if (parseGeometry(parsedTorus, scene)) {
  18433. return null; // null since geometry could be something else than a torus...
  18434. }
  18435. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18436. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18437. scene.pushGeometry(torus, true);
  18438. return torus;
  18439. };
  18440. var parseGround = function (parsedGround, scene) {
  18441. if (parseGeometry(parsedGround, scene)) {
  18442. return null; // null since geometry could be something else than a ground...
  18443. }
  18444. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18445. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18446. scene.pushGeometry(ground, true);
  18447. return ground;
  18448. };
  18449. var parsePlane = function (parsedPlane, scene) {
  18450. if (parseGeometry(parsedPlane, scene)) {
  18451. return null; // null since geometry could be something else than a plane...
  18452. }
  18453. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18454. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18455. scene.pushGeometry(plane, true);
  18456. return plane;
  18457. };
  18458. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18459. if (parseGeometry(parsedTorusKnot, scene)) {
  18460. return null; // null since geometry could be something else than a torusKnot...
  18461. }
  18462. 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);
  18463. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18464. scene.pushGeometry(torusKnot, true);
  18465. return torusKnot;
  18466. };
  18467. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18468. if (parseGeometry(parsedVertexData, scene)) {
  18469. return null; // null since geometry could be a primitive
  18470. }
  18471. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18472. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18473. if (parsedVertexData.delayLoadingFile) {
  18474. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18475. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18476. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18477. geometry._delayInfo = [];
  18478. if (parsedVertexData.hasUVs) {
  18479. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18480. }
  18481. if (parsedVertexData.hasUVs2) {
  18482. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18483. }
  18484. if (parsedVertexData.hasColors) {
  18485. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18486. }
  18487. if (parsedVertexData.hasMatricesIndices) {
  18488. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18489. }
  18490. if (parsedVertexData.hasMatricesWeights) {
  18491. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18492. }
  18493. geometry._delayLoadingFunction = importVertexData;
  18494. }
  18495. else {
  18496. importVertexData(parsedVertexData, geometry);
  18497. }
  18498. scene.pushGeometry(geometry, true);
  18499. return geometry;
  18500. };
  18501. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18502. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18503. mesh.id = parsedMesh.id;
  18504. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18505. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18506. if (parsedMesh.rotationQuaternion) {
  18507. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18508. }
  18509. else if (parsedMesh.rotation) {
  18510. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18511. }
  18512. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18513. if (parsedMesh.localMatrix) {
  18514. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18515. }
  18516. else if (parsedMesh.pivotMatrix) {
  18517. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18518. }
  18519. mesh.setEnabled(parsedMesh.isEnabled);
  18520. mesh.isVisible = parsedMesh.isVisible;
  18521. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18522. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18523. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18524. if (parsedMesh.applyFog !== undefined) {
  18525. mesh.applyFog = parsedMesh.applyFog;
  18526. }
  18527. if (parsedMesh.pickable !== undefined) {
  18528. mesh.isPickable = parsedMesh.pickable;
  18529. }
  18530. if (parsedMesh.alphaIndex !== undefined) {
  18531. mesh.alphaIndex = parsedMesh.alphaIndex;
  18532. }
  18533. mesh.receiveShadows = parsedMesh.receiveShadows;
  18534. mesh.billboardMode = parsedMesh.billboardMode;
  18535. if (parsedMesh.visibility !== undefined) {
  18536. mesh.visibility = parsedMesh.visibility;
  18537. }
  18538. mesh.checkCollisions = parsedMesh.checkCollisions;
  18539. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18540. // Parent
  18541. if (parsedMesh.parentId) {
  18542. mesh._waitingParentId = parsedMesh.parentId;
  18543. }
  18544. // Actions
  18545. if (parsedMesh.actions !== undefined) {
  18546. mesh._waitingActions = parsedMesh.actions;
  18547. }
  18548. // Geometry
  18549. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18550. if (parsedMesh.delayLoadingFile) {
  18551. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18552. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18553. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18554. if (parsedMesh._binaryInfo) {
  18555. mesh._binaryInfo = parsedMesh._binaryInfo;
  18556. }
  18557. mesh._delayInfo = [];
  18558. if (parsedMesh.hasUVs) {
  18559. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18560. }
  18561. if (parsedMesh.hasUVs2) {
  18562. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18563. }
  18564. if (parsedMesh.hasColors) {
  18565. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18566. }
  18567. if (parsedMesh.hasMatricesIndices) {
  18568. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18569. }
  18570. if (parsedMesh.hasMatricesWeights) {
  18571. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18572. }
  18573. mesh._delayLoadingFunction = importGeometry;
  18574. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18575. mesh._checkDelayState();
  18576. }
  18577. }
  18578. else {
  18579. importGeometry(parsedMesh, mesh);
  18580. }
  18581. // Material
  18582. if (parsedMesh.materialId) {
  18583. mesh.setMaterialByID(parsedMesh.materialId);
  18584. }
  18585. else {
  18586. mesh.material = null;
  18587. }
  18588. // Skeleton
  18589. if (parsedMesh.skeletonId > -1) {
  18590. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18591. }
  18592. // Physics
  18593. if (parsedMesh.physicsImpostor) {
  18594. if (!scene.isPhysicsEnabled()) {
  18595. scene.enablePhysics();
  18596. }
  18597. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18598. }
  18599. // Animations
  18600. if (parsedMesh.animations) {
  18601. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18602. var parsedAnimation = parsedMesh.animations[animationIndex];
  18603. mesh.animations.push(parseAnimation(parsedAnimation));
  18604. }
  18605. }
  18606. if (parsedMesh.autoAnimate) {
  18607. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18608. }
  18609. // Layer Mask
  18610. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18611. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18612. }
  18613. else {
  18614. mesh.layerMask = 0xFFFFFFFF;
  18615. }
  18616. // Instances
  18617. if (parsedMesh.instances) {
  18618. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18619. var parsedInstance = parsedMesh.instances[index];
  18620. var instance = mesh.createInstance(parsedInstance.name);
  18621. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18622. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18623. if (parsedInstance.rotationQuaternion) {
  18624. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18625. }
  18626. else if (parsedInstance.rotation) {
  18627. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18628. }
  18629. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18630. instance.checkCollisions = mesh.checkCollisions;
  18631. if (parsedMesh.animations) {
  18632. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18633. parsedAnimation = parsedMesh.animations[animationIndex];
  18634. instance.animations.push(parseAnimation(parsedAnimation));
  18635. }
  18636. }
  18637. }
  18638. }
  18639. return mesh;
  18640. };
  18641. var parseActions = function (parsedActions, object, scene) {
  18642. var actionManager = new BABYLON.ActionManager(scene);
  18643. if (object === null)
  18644. scene.actionManager = actionManager;
  18645. else
  18646. object.actionManager = actionManager;
  18647. // instanciate a new object
  18648. var instanciate = function (name, params) {
  18649. var newInstance = Object.create(BABYLON[name].prototype);
  18650. newInstance.constructor.apply(newInstance, params);
  18651. return newInstance;
  18652. };
  18653. var parseParameter = function (name, value, target, propertyPath) {
  18654. if (propertyPath === null) {
  18655. // String, boolean or float
  18656. var floatValue = parseFloat(value);
  18657. if (value === "true" || value === "false")
  18658. return value === "true";
  18659. else
  18660. return isNaN(floatValue) ? value : floatValue;
  18661. }
  18662. var effectiveTarget = propertyPath.split(".");
  18663. var values = value.split(",");
  18664. for (var i = 0; i < effectiveTarget.length; i++) {
  18665. target = target[effectiveTarget[i]];
  18666. }
  18667. // Return appropriate value with its type
  18668. if (typeof (target) === "boolean")
  18669. return values[0] === "true";
  18670. if (typeof (target) === "string")
  18671. return values[0];
  18672. // Parameters with multiple values such as Vector3 etc.
  18673. var split = new Array();
  18674. for (var i = 0; i < values.length; i++)
  18675. split.push(parseFloat(values[i]));
  18676. if (target instanceof BABYLON.Vector3)
  18677. return BABYLON.Vector3.FromArray(split);
  18678. if (target instanceof BABYLON.Vector4)
  18679. return BABYLON.Vector4.FromArray(split);
  18680. if (target instanceof BABYLON.Color3)
  18681. return BABYLON.Color3.FromArray(split);
  18682. if (target instanceof BABYLON.Color4)
  18683. return BABYLON.Color4.FromArray(split);
  18684. return parseFloat(values[0]);
  18685. };
  18686. // traverse graph per trigger
  18687. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  18688. if (combineArray === void 0) { combineArray = null; }
  18689. if (parsedAction.detached)
  18690. return;
  18691. var parameters = new Array();
  18692. var target = null;
  18693. var propertyPath = null;
  18694. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  18695. // Parameters
  18696. if (parsedAction.type === 2)
  18697. parameters.push(actionManager);
  18698. else
  18699. parameters.push(trigger);
  18700. if (combine) {
  18701. var actions = new Array();
  18702. for (var j = 0; j < parsedAction.combine.length; j++) {
  18703. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  18704. }
  18705. parameters.push(actions);
  18706. }
  18707. else {
  18708. for (var i = 0; i < parsedAction.properties.length; i++) {
  18709. var value = parsedAction.properties[i].value;
  18710. var name = parsedAction.properties[i].name;
  18711. var targetType = parsedAction.properties[i].targetType;
  18712. if (name === "target")
  18713. if (targetType !== null && targetType === "SceneProperties")
  18714. value = target = scene;
  18715. else
  18716. value = target = scene.getNodeByName(value);
  18717. else if (name === "parent")
  18718. value = scene.getNodeByName(value);
  18719. else if (name === "sound")
  18720. value = scene.getSoundByName(value);
  18721. else if (name !== "propertyPath") {
  18722. if (parsedAction.type === 2 && name === "operator")
  18723. value = BABYLON.ValueCondition[value];
  18724. else
  18725. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18726. }
  18727. else {
  18728. propertyPath = value;
  18729. }
  18730. parameters.push(value);
  18731. }
  18732. }
  18733. if (combineArray === null) {
  18734. parameters.push(condition);
  18735. }
  18736. else {
  18737. parameters.push(null);
  18738. }
  18739. // If interpolate value action
  18740. if (parsedAction.name === "InterpolateValueAction") {
  18741. var param = parameters[parameters.length - 2];
  18742. parameters[parameters.length - 1] = param;
  18743. parameters[parameters.length - 2] = condition;
  18744. }
  18745. // Action or condition(s) and not CombineAction
  18746. var newAction = instanciate(parsedAction.name, parameters);
  18747. if (combineArray === null) {
  18748. if (newAction instanceof BABYLON.Condition) {
  18749. condition = newAction;
  18750. newAction = action;
  18751. }
  18752. else {
  18753. condition = null;
  18754. if (action)
  18755. action.then(newAction);
  18756. else
  18757. actionManager.registerAction(newAction);
  18758. }
  18759. }
  18760. else {
  18761. combineArray.push(newAction);
  18762. }
  18763. for (var i = 0; i < parsedAction.children.length; i++)
  18764. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  18765. };
  18766. for (var i = 0; i < parsedActions.children.length; i++) {
  18767. var triggerParams;
  18768. var trigger = parsedActions.children[i];
  18769. if (trigger.properties.length > 0) {
  18770. var param = trigger.properties[0].value;
  18771. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  18772. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  18773. }
  18774. else
  18775. triggerParams = BABYLON.ActionManager[trigger.name];
  18776. for (var j = 0; j < trigger.children.length; j++) {
  18777. if (!trigger.detached)
  18778. traverse(trigger.children[j], triggerParams, null, null);
  18779. }
  18780. }
  18781. };
  18782. var parseSound = function (parsedSound, scene, rootUrl) {
  18783. var soundName = parsedSound.name;
  18784. var soundUrl = rootUrl + soundName;
  18785. var options = {
  18786. autoplay: parsedSound.autoplay,
  18787. loop: parsedSound.loop,
  18788. volume: parsedSound.volume,
  18789. spatialSound: parsedSound.spatialSound,
  18790. maxDistance: parsedSound.maxDistance,
  18791. rolloffFactor: parsedSound.rolloffFactor,
  18792. refDistance: parsedSound.refDistance,
  18793. distanceModel: parsedSound.distanceModel,
  18794. playbackRate: parsedSound.playbackRate
  18795. };
  18796. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18797. scene._removePendingData(newSound);
  18798. }, options);
  18799. scene._addPendingData(newSound);
  18800. if (parsedSound.position) {
  18801. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18802. newSound.setPosition(soundPosition);
  18803. }
  18804. if (parsedSound.isDirectional) {
  18805. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18806. if (parsedSound.localDirectionToMesh) {
  18807. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18808. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18809. }
  18810. }
  18811. if (parsedSound.connectedMeshId) {
  18812. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18813. if (connectedMesh) {
  18814. newSound.attachToMesh(connectedMesh);
  18815. }
  18816. }
  18817. };
  18818. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18819. names = (names instanceof Array) ? names : [names];
  18820. for (var i in names) {
  18821. if (mesh.name === names[i]) {
  18822. hierarchyIds.push(mesh.id);
  18823. return true;
  18824. }
  18825. }
  18826. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18827. hierarchyIds.push(mesh.id);
  18828. return true;
  18829. }
  18830. return false;
  18831. };
  18832. var importVertexData = function (parsedVertexData, geometry) {
  18833. var vertexData = new BABYLON.VertexData();
  18834. // positions
  18835. var positions = parsedVertexData.positions;
  18836. if (positions) {
  18837. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18838. }
  18839. // normals
  18840. var normals = parsedVertexData.normals;
  18841. if (normals) {
  18842. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18843. }
  18844. // uvs
  18845. var uvs = parsedVertexData.uvs;
  18846. if (uvs) {
  18847. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18848. }
  18849. // uv2s
  18850. var uv2s = parsedVertexData.uv2s;
  18851. if (uv2s) {
  18852. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18853. }
  18854. // colors
  18855. var colors = parsedVertexData.colors;
  18856. if (colors) {
  18857. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18858. }
  18859. // matricesIndices
  18860. var matricesIndices = parsedVertexData.matricesIndices;
  18861. if (matricesIndices) {
  18862. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18863. }
  18864. // matricesWeights
  18865. var matricesWeights = parsedVertexData.matricesWeights;
  18866. if (matricesWeights) {
  18867. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18868. }
  18869. // indices
  18870. var indices = parsedVertexData.indices;
  18871. if (indices) {
  18872. vertexData.indices = indices;
  18873. }
  18874. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18875. };
  18876. var importGeometry = function (parsedGeometry, mesh) {
  18877. var scene = mesh.getScene();
  18878. // Geometry
  18879. var geometryId = parsedGeometry.geometryId;
  18880. if (geometryId) {
  18881. var geometry = scene.getGeometryByID(geometryId);
  18882. if (geometry) {
  18883. geometry.applyToMesh(mesh);
  18884. }
  18885. }
  18886. else if (parsedGeometry instanceof ArrayBuffer) {
  18887. var binaryInfo = mesh._binaryInfo;
  18888. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18889. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18890. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18891. }
  18892. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18893. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18894. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18895. }
  18896. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18897. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18898. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18899. }
  18900. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18901. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18902. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18903. }
  18904. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18905. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18906. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18907. }
  18908. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18909. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18910. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18911. }
  18912. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18913. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18914. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18915. }
  18916. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18917. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18918. mesh.setIndices(indicesData);
  18919. }
  18920. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18921. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18922. mesh.subMeshes = [];
  18923. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18924. var materialIndex = subMeshesData[(i * 5) + 0];
  18925. var verticesStart = subMeshesData[(i * 5) + 1];
  18926. var verticesCount = subMeshesData[(i * 5) + 2];
  18927. var indexStart = subMeshesData[(i * 5) + 3];
  18928. var indexCount = subMeshesData[(i * 5) + 4];
  18929. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18930. }
  18931. }
  18932. }
  18933. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18934. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18935. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18936. if (parsedGeometry.uvs) {
  18937. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18938. }
  18939. if (parsedGeometry.uvs2) {
  18940. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18941. }
  18942. if (parsedGeometry.colors) {
  18943. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18944. }
  18945. if (parsedGeometry.matricesIndices) {
  18946. if (!parsedGeometry.matricesIndices._isExpanded) {
  18947. var floatIndices = [];
  18948. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18949. var matricesIndex = parsedGeometry.matricesIndices[i];
  18950. floatIndices.push(matricesIndex & 0x000000FF);
  18951. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18952. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18953. floatIndices.push(matricesIndex >> 24);
  18954. }
  18955. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18956. }
  18957. else {
  18958. delete parsedGeometry.matricesIndices._isExpanded;
  18959. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18960. }
  18961. }
  18962. if (parsedGeometry.matricesWeights) {
  18963. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18964. }
  18965. mesh.setIndices(parsedGeometry.indices);
  18966. // SubMeshes
  18967. if (parsedGeometry.subMeshes) {
  18968. mesh.subMeshes = [];
  18969. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18970. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18971. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18972. }
  18973. }
  18974. }
  18975. // Flat shading
  18976. if (mesh._shouldGenerateFlatShading) {
  18977. mesh.convertToFlatShadedMesh();
  18978. delete mesh._shouldGenerateFlatShading;
  18979. }
  18980. // Update
  18981. mesh.computeWorldMatrix(true);
  18982. // Octree
  18983. if (scene._selectionOctree) {
  18984. scene._selectionOctree.addMesh(mesh);
  18985. }
  18986. };
  18987. BABYLON.SceneLoader.RegisterPlugin({
  18988. extensions: ".babylon",
  18989. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18990. var parsedData = JSON.parse(data);
  18991. var loadedSkeletonsIds = [];
  18992. var loadedMaterialsIds = [];
  18993. var hierarchyIds = [];
  18994. for (var index = 0; index < parsedData.meshes.length; index++) {
  18995. var parsedMesh = parsedData.meshes[index];
  18996. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18997. if (meshesNames instanceof Array) {
  18998. // Remove found mesh name from list.
  18999. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19000. }
  19001. // Material ?
  19002. if (parsedMesh.materialId) {
  19003. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19004. if (!materialFound) {
  19005. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19006. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19007. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19008. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19009. var subMatId = parsedMultiMaterial.materials[matIndex];
  19010. loadedMaterialsIds.push(subMatId);
  19011. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19012. }
  19013. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19014. parseMultiMaterial(parsedMultiMaterial, scene);
  19015. materialFound = true;
  19016. break;
  19017. }
  19018. }
  19019. }
  19020. if (!materialFound) {
  19021. loadedMaterialsIds.push(parsedMesh.materialId);
  19022. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19023. }
  19024. }
  19025. // Skeleton ?
  19026. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19027. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19028. if (!skeletonAlreadyLoaded) {
  19029. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19030. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19031. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19032. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19033. loadedSkeletonsIds.push(parsedSkeleton.id);
  19034. }
  19035. }
  19036. }
  19037. }
  19038. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19039. meshes.push(mesh);
  19040. }
  19041. }
  19042. for (index = 0; index < scene.meshes.length; index++) {
  19043. var currentMesh = scene.meshes[index];
  19044. if (currentMesh._waitingParentId) {
  19045. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19046. currentMesh._waitingParentId = undefined;
  19047. }
  19048. }
  19049. // Particles
  19050. if (parsedData.particleSystems) {
  19051. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19052. var parsedParticleSystem = parsedData.particleSystems[index];
  19053. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19054. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19055. }
  19056. }
  19057. }
  19058. return true;
  19059. },
  19060. load: function (scene, data, rootUrl) {
  19061. var parsedData = JSON.parse(data);
  19062. // Scene
  19063. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19064. scene.autoClear = parsedData.autoClear;
  19065. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19066. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19067. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19068. // Fog
  19069. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19070. scene.fogMode = parsedData.fogMode;
  19071. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19072. scene.fogStart = parsedData.fogStart;
  19073. scene.fogEnd = parsedData.fogEnd;
  19074. scene.fogDensity = parsedData.fogDensity;
  19075. }
  19076. for (var index = 0; index < parsedData.lights.length; index++) {
  19077. var parsedLight = parsedData.lights[index];
  19078. parseLight(parsedLight, scene);
  19079. }
  19080. // Materials
  19081. if (parsedData.materials) {
  19082. for (index = 0; index < parsedData.materials.length; index++) {
  19083. var parsedMaterial = parsedData.materials[index];
  19084. parseMaterial(parsedMaterial, scene, rootUrl);
  19085. }
  19086. }
  19087. if (parsedData.multiMaterials) {
  19088. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19089. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19090. parseMultiMaterial(parsedMultiMaterial, scene);
  19091. }
  19092. }
  19093. // Skeletons
  19094. if (parsedData.skeletons) {
  19095. for (index = 0; index < parsedData.skeletons.length; index++) {
  19096. var parsedSkeleton = parsedData.skeletons[index];
  19097. parseSkeleton(parsedSkeleton, scene);
  19098. }
  19099. }
  19100. // Geometries
  19101. var geometries = parsedData.geometries;
  19102. if (geometries) {
  19103. // Boxes
  19104. var boxes = geometries.boxes;
  19105. if (boxes) {
  19106. for (index = 0; index < boxes.length; index++) {
  19107. var parsedBox = boxes[index];
  19108. parseBox(parsedBox, scene);
  19109. }
  19110. }
  19111. // Spheres
  19112. var spheres = geometries.spheres;
  19113. if (spheres) {
  19114. for (index = 0; index < spheres.length; index++) {
  19115. var parsedSphere = spheres[index];
  19116. parseSphere(parsedSphere, scene);
  19117. }
  19118. }
  19119. // Cylinders
  19120. var cylinders = geometries.cylinders;
  19121. if (cylinders) {
  19122. for (index = 0; index < cylinders.length; index++) {
  19123. var parsedCylinder = cylinders[index];
  19124. parseCylinder(parsedCylinder, scene);
  19125. }
  19126. }
  19127. // Toruses
  19128. var toruses = geometries.toruses;
  19129. if (toruses) {
  19130. for (index = 0; index < toruses.length; index++) {
  19131. var parsedTorus = toruses[index];
  19132. parseTorus(parsedTorus, scene);
  19133. }
  19134. }
  19135. // Grounds
  19136. var grounds = geometries.grounds;
  19137. if (grounds) {
  19138. for (index = 0; index < grounds.length; index++) {
  19139. var parsedGround = grounds[index];
  19140. parseGround(parsedGround, scene);
  19141. }
  19142. }
  19143. // Planes
  19144. var planes = geometries.planes;
  19145. if (planes) {
  19146. for (index = 0; index < planes.length; index++) {
  19147. var parsedPlane = planes[index];
  19148. parsePlane(parsedPlane, scene);
  19149. }
  19150. }
  19151. // TorusKnots
  19152. var torusKnots = geometries.torusKnots;
  19153. if (torusKnots) {
  19154. for (index = 0; index < torusKnots.length; index++) {
  19155. var parsedTorusKnot = torusKnots[index];
  19156. parseTorusKnot(parsedTorusKnot, scene);
  19157. }
  19158. }
  19159. // VertexData
  19160. var vertexData = geometries.vertexData;
  19161. if (vertexData) {
  19162. for (index = 0; index < vertexData.length; index++) {
  19163. var parsedVertexData = vertexData[index];
  19164. parseVertexData(parsedVertexData, scene, rootUrl);
  19165. }
  19166. }
  19167. }
  19168. for (index = 0; index < parsedData.meshes.length; index++) {
  19169. var parsedMesh = parsedData.meshes[index];
  19170. parseMesh(parsedMesh, scene, rootUrl);
  19171. }
  19172. for (index = 0; index < parsedData.cameras.length; index++) {
  19173. var parsedCamera = parsedData.cameras[index];
  19174. parseCamera(parsedCamera, scene);
  19175. }
  19176. if (parsedData.activeCameraID) {
  19177. scene.setActiveCameraByID(parsedData.activeCameraID);
  19178. }
  19179. for (index = 0; index < scene.cameras.length; index++) {
  19180. var camera = scene.cameras[index];
  19181. if (camera._waitingParentId) {
  19182. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19183. camera._waitingParentId = undefined;
  19184. }
  19185. }
  19186. for (index = 0; index < scene.lights.length; index++) {
  19187. var light = scene.lights[index];
  19188. if (light._waitingParentId) {
  19189. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19190. light._waitingParentId = undefined;
  19191. }
  19192. }
  19193. // Sounds
  19194. if (parsedData.sounds) {
  19195. for (index = 0; index < parsedData.sounds.length; index++) {
  19196. var parsedSound = parsedData.sounds[index];
  19197. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19198. parseSound(parsedSound, scene, rootUrl);
  19199. }
  19200. else {
  19201. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19202. }
  19203. }
  19204. }
  19205. for (index = 0; index < scene.meshes.length; index++) {
  19206. var mesh = scene.meshes[index];
  19207. if (mesh._waitingParentId) {
  19208. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19209. mesh._waitingParentId = undefined;
  19210. }
  19211. if (mesh._waitingActions) {
  19212. parseActions(mesh._waitingActions, mesh, scene);
  19213. mesh._waitingActions = undefined;
  19214. }
  19215. }
  19216. // Particles Systems
  19217. if (parsedData.particleSystems) {
  19218. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19219. var parsedParticleSystem = parsedData.particleSystems[index];
  19220. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19221. }
  19222. }
  19223. // Lens flares
  19224. if (parsedData.lensFlareSystems) {
  19225. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19226. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19227. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19228. }
  19229. }
  19230. // Shadows
  19231. if (parsedData.shadowGenerators) {
  19232. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19233. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19234. parseShadowGenerator(parsedShadowGenerator, scene);
  19235. }
  19236. }
  19237. // Actions (scene)
  19238. if (parsedData.actions) {
  19239. parseActions(parsedData.actions, null, scene);
  19240. }
  19241. // Finish
  19242. return true;
  19243. }
  19244. });
  19245. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19246. })(BABYLON || (BABYLON = {}));
  19247. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  19248. var BABYLON;
  19249. (function (BABYLON) {
  19250. var SpriteManager = (function () {
  19251. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  19252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  19253. this.name = name;
  19254. this.cellSize = cellSize;
  19255. this.sprites = new Array();
  19256. this.renderingGroupId = 0;
  19257. this.fogEnabled = true;
  19258. this._vertexDeclaration = [4, 4, 4, 4];
  19259. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  19260. this._capacity = capacity;
  19261. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  19262. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19263. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  19264. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  19265. this._scene = scene;
  19266. this._scene.spriteManagers.push(this);
  19267. // VBO
  19268. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  19269. var indices = [];
  19270. var index = 0;
  19271. for (var count = 0; count < capacity; count++) {
  19272. indices.push(index);
  19273. indices.push(index + 1);
  19274. indices.push(index + 2);
  19275. indices.push(index);
  19276. indices.push(index + 2);
  19277. indices.push(index + 3);
  19278. index += 4;
  19279. }
  19280. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19281. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  19282. // Effects
  19283. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  19284. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  19285. }
  19286. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  19287. var arrayOffset = index * 16;
  19288. if (offsetX === 0)
  19289. offsetX = this._epsilon;
  19290. else if (offsetX === 1)
  19291. offsetX = 1 - this._epsilon;
  19292. if (offsetY === 0)
  19293. offsetY = this._epsilon;
  19294. else if (offsetY === 1)
  19295. offsetY = 1 - this._epsilon;
  19296. this._vertices[arrayOffset] = sprite.position.x;
  19297. this._vertices[arrayOffset + 1] = sprite.position.y;
  19298. this._vertices[arrayOffset + 2] = sprite.position.z;
  19299. this._vertices[arrayOffset + 3] = sprite.angle;
  19300. this._vertices[arrayOffset + 4] = sprite.width;
  19301. this._vertices[arrayOffset + 5] = sprite.height;
  19302. this._vertices[arrayOffset + 6] = offsetX;
  19303. this._vertices[arrayOffset + 7] = offsetY;
  19304. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  19305. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  19306. var offset = (sprite.cellIndex / rowSize) >> 0;
  19307. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  19308. this._vertices[arrayOffset + 11] = offset;
  19309. // Color
  19310. this._vertices[arrayOffset + 12] = sprite.color.r;
  19311. this._vertices[arrayOffset + 13] = sprite.color.g;
  19312. this._vertices[arrayOffset + 14] = sprite.color.b;
  19313. this._vertices[arrayOffset + 15] = sprite.color.a;
  19314. };
  19315. SpriteManager.prototype.render = function () {
  19316. // Check
  19317. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  19318. return;
  19319. var engine = this._scene.getEngine();
  19320. var baseSize = this._spriteTexture.getBaseSize();
  19321. // Sprites
  19322. var deltaTime = engine.getDeltaTime();
  19323. var max = Math.min(this._capacity, this.sprites.length);
  19324. var rowSize = baseSize.width / this.cellSize;
  19325. var offset = 0;
  19326. for (var index = 0; index < max; index++) {
  19327. var sprite = this.sprites[index];
  19328. if (!sprite) {
  19329. continue;
  19330. }
  19331. sprite._animate(deltaTime);
  19332. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  19333. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  19334. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  19335. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  19336. }
  19337. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  19338. // Render
  19339. var effect = this._effectBase;
  19340. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19341. effect = this._effectFog;
  19342. }
  19343. engine.enableEffect(effect);
  19344. var viewMatrix = this._scene.getViewMatrix();
  19345. effect.setTexture("diffuseSampler", this._spriteTexture);
  19346. effect.setMatrix("view", viewMatrix);
  19347. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  19348. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  19349. // Fog
  19350. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  19351. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  19352. effect.setColor3("vFogColor", this._scene.fogColor);
  19353. }
  19354. // VBOs
  19355. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  19356. // Draw order
  19357. engine.setDepthFunctionToLessOrEqual();
  19358. effect.setBool("alphaTest", true);
  19359. engine.setColorWrite(false);
  19360. engine.draw(true, 0, max * 6);
  19361. engine.setColorWrite(true);
  19362. effect.setBool("alphaTest", false);
  19363. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19364. engine.draw(true, 0, max * 6);
  19365. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19366. };
  19367. SpriteManager.prototype.dispose = function () {
  19368. if (this._vertexBuffer) {
  19369. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  19370. this._vertexBuffer = null;
  19371. }
  19372. if (this._indexBuffer) {
  19373. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  19374. this._indexBuffer = null;
  19375. }
  19376. if (this._spriteTexture) {
  19377. this._spriteTexture.dispose();
  19378. this._spriteTexture = null;
  19379. }
  19380. // Remove from scene
  19381. var index = this._scene.spriteManagers.indexOf(this);
  19382. this._scene.spriteManagers.splice(index, 1);
  19383. // Callback
  19384. if (this.onDispose) {
  19385. this.onDispose();
  19386. }
  19387. };
  19388. return SpriteManager;
  19389. })();
  19390. BABYLON.SpriteManager = SpriteManager;
  19391. })(BABYLON || (BABYLON = {}));
  19392. //# sourceMappingURL=babylon.spriteManager.js.map
  19393. var BABYLON;
  19394. (function (BABYLON) {
  19395. var Sprite = (function () {
  19396. function Sprite(name, manager) {
  19397. this.name = name;
  19398. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19399. this.width = 1.0;
  19400. this.height = 1.0;
  19401. this.angle = 0;
  19402. this.cellIndex = 0;
  19403. this.invertU = 0;
  19404. this.invertV = 0;
  19405. this.animations = new Array();
  19406. this._animationStarted = false;
  19407. this._loopAnimation = false;
  19408. this._fromIndex = 0;
  19409. this._toIndex = 0;
  19410. this._delay = 0;
  19411. this._direction = 1;
  19412. this._frameCount = 0;
  19413. this._time = 0;
  19414. this._manager = manager;
  19415. this._manager.sprites.push(this);
  19416. this.position = BABYLON.Vector3.Zero();
  19417. }
  19418. Object.defineProperty(Sprite.prototype, "size", {
  19419. get: function () {
  19420. return this.width;
  19421. },
  19422. set: function (value) {
  19423. this.width = value;
  19424. this.height = value;
  19425. },
  19426. enumerable: true,
  19427. configurable: true
  19428. });
  19429. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  19430. this._fromIndex = from;
  19431. this._toIndex = to;
  19432. this._loopAnimation = loop;
  19433. this._delay = delay;
  19434. this._animationStarted = true;
  19435. this._direction = from < to ? 1 : -1;
  19436. this.cellIndex = from;
  19437. this._time = 0;
  19438. };
  19439. Sprite.prototype.stopAnimation = function () {
  19440. this._animationStarted = false;
  19441. };
  19442. Sprite.prototype._animate = function (deltaTime) {
  19443. if (!this._animationStarted)
  19444. return;
  19445. this._time += deltaTime;
  19446. if (this._time > this._delay) {
  19447. this._time = this._time % this._delay;
  19448. this.cellIndex += this._direction;
  19449. if (this.cellIndex == this._toIndex) {
  19450. if (this._loopAnimation) {
  19451. this.cellIndex = this._fromIndex;
  19452. }
  19453. else {
  19454. this._animationStarted = false;
  19455. if (this.disposeWhenFinishedAnimating) {
  19456. this.dispose();
  19457. }
  19458. }
  19459. }
  19460. }
  19461. };
  19462. Sprite.prototype.dispose = function () {
  19463. for (var i = 0; i < this._manager.sprites.length; i++) {
  19464. if (this._manager.sprites[i] == this) {
  19465. this._manager.sprites.splice(i, 1);
  19466. }
  19467. }
  19468. };
  19469. return Sprite;
  19470. })();
  19471. BABYLON.Sprite = Sprite;
  19472. })(BABYLON || (BABYLON = {}));
  19473. //# sourceMappingURL=babylon.sprite.js.map
  19474. var BABYLON;
  19475. (function (BABYLON) {
  19476. var Layer = (function () {
  19477. function Layer(name, imgUrl, scene, isBackground, color) {
  19478. this.name = name;
  19479. this._vertexDeclaration = [2];
  19480. this._vertexStrideSize = 2 * 4;
  19481. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  19482. this.isBackground = isBackground === undefined ? true : isBackground;
  19483. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  19484. this._scene = scene;
  19485. this._scene.layers.push(this);
  19486. // VBO
  19487. var vertices = [];
  19488. vertices.push(1, 1);
  19489. vertices.push(-1, 1);
  19490. vertices.push(-1, -1);
  19491. vertices.push(1, -1);
  19492. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  19493. // Indices
  19494. var indices = [];
  19495. indices.push(0);
  19496. indices.push(1);
  19497. indices.push(2);
  19498. indices.push(0);
  19499. indices.push(2);
  19500. indices.push(3);
  19501. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19502. // Effects
  19503. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  19504. }
  19505. Layer.prototype.render = function () {
  19506. // Check
  19507. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  19508. return;
  19509. var engine = this._scene.getEngine();
  19510. // Render
  19511. engine.enableEffect(this._effect);
  19512. engine.setState(false);
  19513. // Texture
  19514. this._effect.setTexture("textureSampler", this.texture);
  19515. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  19516. // Color
  19517. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  19518. // VBOs
  19519. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  19520. // Draw order
  19521. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19522. engine.draw(true, 0, 6);
  19523. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19524. };
  19525. Layer.prototype.dispose = function () {
  19526. if (this._vertexBuffer) {
  19527. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  19528. this._vertexBuffer = null;
  19529. }
  19530. if (this._indexBuffer) {
  19531. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  19532. this._indexBuffer = null;
  19533. }
  19534. if (this.texture) {
  19535. this.texture.dispose();
  19536. this.texture = null;
  19537. }
  19538. // Remove from scene
  19539. var index = this._scene.layers.indexOf(this);
  19540. this._scene.layers.splice(index, 1);
  19541. // Callback
  19542. if (this.onDispose) {
  19543. this.onDispose();
  19544. }
  19545. };
  19546. return Layer;
  19547. })();
  19548. BABYLON.Layer = Layer;
  19549. })(BABYLON || (BABYLON = {}));
  19550. //# sourceMappingURL=babylon.layer.js.map
  19551. var BABYLON;
  19552. (function (BABYLON) {
  19553. var Particle = (function () {
  19554. function Particle() {
  19555. this.position = BABYLON.Vector3.Zero();
  19556. this.direction = BABYLON.Vector3.Zero();
  19557. this.color = new BABYLON.Color4(0, 0, 0, 0);
  19558. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  19559. this.lifeTime = 1.0;
  19560. this.age = 0;
  19561. this.size = 0;
  19562. this.angle = 0;
  19563. this.angularSpeed = 0;
  19564. }
  19565. Particle.prototype.copyTo = function (other) {
  19566. other.position.copyFrom(this.position);
  19567. other.direction.copyFrom(this.direction);
  19568. other.color.copyFrom(this.color);
  19569. other.colorStep.copyFrom(this.colorStep);
  19570. other.lifeTime = this.lifeTime;
  19571. other.age = this.age;
  19572. other.size = this.size;
  19573. other.angle = this.angle;
  19574. other.angularSpeed = this.angularSpeed;
  19575. };
  19576. return Particle;
  19577. })();
  19578. BABYLON.Particle = Particle;
  19579. })(BABYLON || (BABYLON = {}));
  19580. //# sourceMappingURL=babylon.particle.js.map
  19581. var BABYLON;
  19582. (function (BABYLON) {
  19583. var randomNumber = function (min, max) {
  19584. if (min === max) {
  19585. return (min);
  19586. }
  19587. var random = Math.random();
  19588. return ((random * (max - min)) + min);
  19589. };
  19590. var ParticleSystem = (function () {
  19591. function ParticleSystem(name, capacity, scene, customEffect) {
  19592. var _this = this;
  19593. this.name = name;
  19594. this.renderingGroupId = 0;
  19595. this.emitter = null;
  19596. this.emitRate = 10;
  19597. this.manualEmitCount = -1;
  19598. this.updateSpeed = 0.01;
  19599. this.targetStopDuration = 0;
  19600. this.disposeOnStop = false;
  19601. this.minEmitPower = 1;
  19602. this.maxEmitPower = 1;
  19603. this.minLifeTime = 1;
  19604. this.maxLifeTime = 1;
  19605. this.minSize = 1;
  19606. this.maxSize = 1;
  19607. this.minAngularSpeed = 0;
  19608. this.maxAngularSpeed = 0;
  19609. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  19610. this.forceDepthWrite = false;
  19611. this.gravity = BABYLON.Vector3.Zero();
  19612. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  19613. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  19614. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  19615. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  19616. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19617. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19618. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  19619. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  19620. this.particles = new Array();
  19621. this._vertexDeclaration = [3, 4, 4];
  19622. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  19623. this._stockParticles = new Array();
  19624. this._newPartsExcess = 0;
  19625. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  19626. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  19627. this._scaledDirection = BABYLON.Vector3.Zero();
  19628. this._scaledGravity = BABYLON.Vector3.Zero();
  19629. this._currentRenderId = -1;
  19630. this._started = false;
  19631. this._stopped = false;
  19632. this._actualFrame = 0;
  19633. this.id = name;
  19634. this._capacity = capacity;
  19635. this._scene = scene;
  19636. this._customEffect = customEffect;
  19637. scene.particleSystems.push(this);
  19638. // VBO
  19639. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  19640. var indices = [];
  19641. var index = 0;
  19642. for (var count = 0; count < capacity; count++) {
  19643. indices.push(index);
  19644. indices.push(index + 1);
  19645. indices.push(index + 2);
  19646. indices.push(index);
  19647. indices.push(index + 2);
  19648. indices.push(index + 3);
  19649. index += 4;
  19650. }
  19651. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  19652. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  19653. // Default behaviors
  19654. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  19655. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  19656. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  19657. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  19658. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  19659. };
  19660. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  19661. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  19662. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  19663. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  19664. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  19665. };
  19666. this.updateFunction = function (particles) {
  19667. for (var index = 0; index < particles.length; index++) {
  19668. var particle = particles[index];
  19669. particle.age += _this._scaledUpdateSpeed;
  19670. if (particle.age >= particle.lifeTime) {
  19671. _this.recycleParticle(particle);
  19672. index--;
  19673. continue;
  19674. }
  19675. else {
  19676. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  19677. particle.color.addInPlace(_this._scaledColorStep);
  19678. if (particle.color.a < 0)
  19679. particle.color.a = 0;
  19680. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  19681. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  19682. particle.position.addInPlace(_this._scaledDirection);
  19683. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  19684. particle.direction.addInPlace(_this._scaledGravity);
  19685. }
  19686. }
  19687. };
  19688. }
  19689. ParticleSystem.prototype.recycleParticle = function (particle) {
  19690. var lastParticle = this.particles.pop();
  19691. if (lastParticle !== particle) {
  19692. lastParticle.copyTo(particle);
  19693. this._stockParticles.push(lastParticle);
  19694. }
  19695. };
  19696. ParticleSystem.prototype.getCapacity = function () {
  19697. return this._capacity;
  19698. };
  19699. ParticleSystem.prototype.isAlive = function () {
  19700. return this._alive;
  19701. };
  19702. ParticleSystem.prototype.isStarted = function () {
  19703. return this._started;
  19704. };
  19705. ParticleSystem.prototype.start = function () {
  19706. this._started = true;
  19707. this._stopped = false;
  19708. this._actualFrame = 0;
  19709. };
  19710. ParticleSystem.prototype.stop = function () {
  19711. this._stopped = true;
  19712. };
  19713. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  19714. var offset = index * 11;
  19715. this._vertices[offset] = particle.position.x;
  19716. this._vertices[offset + 1] = particle.position.y;
  19717. this._vertices[offset + 2] = particle.position.z;
  19718. this._vertices[offset + 3] = particle.color.r;
  19719. this._vertices[offset + 4] = particle.color.g;
  19720. this._vertices[offset + 5] = particle.color.b;
  19721. this._vertices[offset + 6] = particle.color.a;
  19722. this._vertices[offset + 7] = particle.angle;
  19723. this._vertices[offset + 8] = particle.size;
  19724. this._vertices[offset + 9] = offsetX;
  19725. this._vertices[offset + 10] = offsetY;
  19726. };
  19727. ParticleSystem.prototype._update = function (newParticles) {
  19728. // Update current
  19729. this._alive = this.particles.length > 0;
  19730. this.updateFunction(this.particles);
  19731. // Add new ones
  19732. var worldMatrix;
  19733. if (this.emitter.position) {
  19734. worldMatrix = this.emitter.getWorldMatrix();
  19735. }
  19736. else {
  19737. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  19738. }
  19739. for (var index = 0; index < newParticles; index++) {
  19740. if (this.particles.length === this._capacity) {
  19741. break;
  19742. }
  19743. if (this._stockParticles.length !== 0) {
  19744. var particle = this._stockParticles.pop();
  19745. particle.age = 0;
  19746. }
  19747. else {
  19748. particle = new BABYLON.Particle();
  19749. }
  19750. this.particles.push(particle);
  19751. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  19752. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  19753. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  19754. particle.size = randomNumber(this.minSize, this.maxSize);
  19755. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  19756. this.startPositionFunction(worldMatrix, particle.position);
  19757. var step = randomNumber(0, 1.0);
  19758. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  19759. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  19760. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  19761. }
  19762. };
  19763. ParticleSystem.prototype._getEffect = function () {
  19764. if (this._customEffect) {
  19765. return this._customEffect;
  19766. }
  19767. ;
  19768. var defines = [];
  19769. if (this._scene.clipPlane) {
  19770. defines.push("#define CLIPPLANE");
  19771. }
  19772. // Effect
  19773. var join = defines.join("\n");
  19774. if (this._cachedDefines !== join) {
  19775. this._cachedDefines = join;
  19776. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  19777. }
  19778. return this._effect;
  19779. };
  19780. ParticleSystem.prototype.animate = function () {
  19781. if (!this._started)
  19782. return;
  19783. var effect = this._getEffect();
  19784. // Check
  19785. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  19786. return;
  19787. if (this._currentRenderId === this._scene.getRenderId()) {
  19788. return;
  19789. }
  19790. this._currentRenderId = this._scene.getRenderId();
  19791. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  19792. // determine the number of particles we need to create
  19793. var emitCout;
  19794. if (this.manualEmitCount > -1) {
  19795. emitCout = this.manualEmitCount;
  19796. this.manualEmitCount = 0;
  19797. }
  19798. else {
  19799. emitCout = this.emitRate;
  19800. }
  19801. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  19802. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  19803. if (this._newPartsExcess > 1.0) {
  19804. newParticles += this._newPartsExcess >> 0;
  19805. this._newPartsExcess -= this._newPartsExcess >> 0;
  19806. }
  19807. this._alive = false;
  19808. if (!this._stopped) {
  19809. this._actualFrame += this._scaledUpdateSpeed;
  19810. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  19811. this.stop();
  19812. }
  19813. else {
  19814. newParticles = 0;
  19815. }
  19816. this._update(newParticles);
  19817. // Stopped?
  19818. if (this._stopped) {
  19819. if (!this._alive) {
  19820. this._started = false;
  19821. if (this.disposeOnStop) {
  19822. this._scene._toBeDisposed.push(this);
  19823. }
  19824. }
  19825. }
  19826. // Update VBO
  19827. var offset = 0;
  19828. for (var index = 0; index < this.particles.length; index++) {
  19829. var particle = this.particles[index];
  19830. this._appendParticleVertex(offset++, particle, 0, 0);
  19831. this._appendParticleVertex(offset++, particle, 1, 0);
  19832. this._appendParticleVertex(offset++, particle, 1, 1);
  19833. this._appendParticleVertex(offset++, particle, 0, 1);
  19834. }
  19835. var engine = this._scene.getEngine();
  19836. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  19837. };
  19838. ParticleSystem.prototype.render = function () {
  19839. var effect = this._getEffect();
  19840. // Check
  19841. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  19842. return 0;
  19843. var engine = this._scene.getEngine();
  19844. // Render
  19845. engine.enableEffect(effect);
  19846. engine.setState(false);
  19847. var viewMatrix = this._scene.getViewMatrix();
  19848. effect.setTexture("diffuseSampler", this.particleTexture);
  19849. effect.setMatrix("view", viewMatrix);
  19850. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  19851. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  19852. if (this._scene.clipPlane) {
  19853. var clipPlane = this._scene.clipPlane;
  19854. var invView = viewMatrix.clone();
  19855. invView.invert();
  19856. effect.setMatrix("invView", invView);
  19857. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19858. }
  19859. // VBOs
  19860. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  19861. // Draw order
  19862. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  19863. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  19864. }
  19865. else {
  19866. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19867. }
  19868. if (this.forceDepthWrite) {
  19869. engine.setDepthWrite(true);
  19870. }
  19871. engine.draw(true, 0, this.particles.length * 6);
  19872. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19873. return this.particles.length;
  19874. };
  19875. ParticleSystem.prototype.dispose = function () {
  19876. if (this._vertexBuffer) {
  19877. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  19878. this._vertexBuffer = null;
  19879. }
  19880. if (this._indexBuffer) {
  19881. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  19882. this._indexBuffer = null;
  19883. }
  19884. if (this.particleTexture) {
  19885. this.particleTexture.dispose();
  19886. this.particleTexture = null;
  19887. }
  19888. // Remove from scene
  19889. var index = this._scene.particleSystems.indexOf(this);
  19890. this._scene.particleSystems.splice(index, 1);
  19891. // Callback
  19892. if (this.onDispose) {
  19893. this.onDispose();
  19894. }
  19895. };
  19896. // Clone
  19897. ParticleSystem.prototype.clone = function (name, newEmitter) {
  19898. var result = new ParticleSystem(name, this._capacity, this._scene);
  19899. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  19900. if (newEmitter === undefined) {
  19901. newEmitter = this.emitter;
  19902. }
  19903. result.emitter = newEmitter;
  19904. if (this.particleTexture) {
  19905. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  19906. }
  19907. result.start();
  19908. return result;
  19909. };
  19910. // Statics
  19911. ParticleSystem.BLENDMODE_ONEONE = 0;
  19912. ParticleSystem.BLENDMODE_STANDARD = 1;
  19913. return ParticleSystem;
  19914. })();
  19915. BABYLON.ParticleSystem = ParticleSystem;
  19916. })(BABYLON || (BABYLON = {}));
  19917. //# sourceMappingURL=babylon.particleSystem.js.map
  19918. var BABYLON;
  19919. (function (BABYLON) {
  19920. var Animation = (function () {
  19921. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  19922. this.name = name;
  19923. this.targetProperty = targetProperty;
  19924. this.framePerSecond = framePerSecond;
  19925. this.dataType = dataType;
  19926. this.loopMode = loopMode;
  19927. this._offsetsCache = {};
  19928. this._highLimitsCache = {};
  19929. this._stopped = false;
  19930. this.targetPropertyPath = targetProperty.split(".");
  19931. this.dataType = dataType;
  19932. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  19933. }
  19934. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  19935. var dataType = undefined;
  19936. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  19937. dataType = Animation.ANIMATIONTYPE_FLOAT;
  19938. }
  19939. else if (from instanceof BABYLON.Quaternion) {
  19940. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  19941. }
  19942. else if (from instanceof BABYLON.Vector3) {
  19943. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  19944. }
  19945. else if (from instanceof BABYLON.Vector2) {
  19946. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  19947. }
  19948. else if (from instanceof BABYLON.Color3) {
  19949. dataType = Animation.ANIMATIONTYPE_COLOR3;
  19950. }
  19951. if (dataType == undefined) {
  19952. return null;
  19953. }
  19954. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  19955. var keys = [];
  19956. keys.push({ frame: 0, value: from });
  19957. keys.push({ frame: totalFrame, value: to });
  19958. animation.setKeys(keys);
  19959. mesh.animations.push(animation);
  19960. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  19961. };
  19962. // Methods
  19963. Animation.prototype.isStopped = function () {
  19964. return this._stopped;
  19965. };
  19966. Animation.prototype.getKeys = function () {
  19967. return this._keys;
  19968. };
  19969. Animation.prototype.getEasingFunction = function () {
  19970. return this._easingFunction;
  19971. };
  19972. Animation.prototype.setEasingFunction = function (easingFunction) {
  19973. this._easingFunction = easingFunction;
  19974. };
  19975. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  19976. return startValue + (endValue - startValue) * gradient;
  19977. };
  19978. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  19979. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  19980. };
  19981. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  19982. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  19983. };
  19984. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  19985. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  19986. };
  19987. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  19988. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  19989. };
  19990. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  19991. var startScale = new BABYLON.Vector3(0, 0, 0);
  19992. var startRotation = new BABYLON.Quaternion();
  19993. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  19994. startValue.decompose(startScale, startRotation, startTranslation);
  19995. var endScale = new BABYLON.Vector3(0, 0, 0);
  19996. var endRotation = new BABYLON.Quaternion();
  19997. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  19998. endValue.decompose(endScale, endRotation, endTranslation);
  19999. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  20000. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  20001. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  20002. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  20003. return result;
  20004. };
  20005. Animation.prototype.clone = function () {
  20006. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  20007. clone.setKeys(this._keys);
  20008. return clone;
  20009. };
  20010. Animation.prototype.setKeys = function (values) {
  20011. this._keys = values.slice(0);
  20012. this._offsetsCache = {};
  20013. this._highLimitsCache = {};
  20014. };
  20015. Animation.prototype._getKeyValue = function (value) {
  20016. if (typeof value === "function") {
  20017. return value();
  20018. }
  20019. return value;
  20020. };
  20021. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  20022. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  20023. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  20024. }
  20025. this.currentFrame = currentFrame;
  20026. // Try to get a hash to find the right key
  20027. 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));
  20028. if (this._keys[startKey].frame >= currentFrame) {
  20029. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  20030. startKey--;
  20031. }
  20032. }
  20033. for (var key = startKey; key < this._keys.length; key++) {
  20034. if (this._keys[key + 1].frame >= currentFrame) {
  20035. var startValue = this._getKeyValue(this._keys[key].value);
  20036. var endValue = this._getKeyValue(this._keys[key + 1].value);
  20037. // gradient : percent of currentFrame between the frame inf and the frame sup
  20038. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  20039. // check for easingFunction and correction of gradient
  20040. if (this._easingFunction != null) {
  20041. gradient = this._easingFunction.ease(gradient);
  20042. }
  20043. switch (this.dataType) {
  20044. case Animation.ANIMATIONTYPE_FLOAT:
  20045. switch (loopMode) {
  20046. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20047. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20048. return this.floatInterpolateFunction(startValue, endValue, gradient);
  20049. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20050. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  20051. }
  20052. break;
  20053. case Animation.ANIMATIONTYPE_QUATERNION:
  20054. var quaternion = null;
  20055. switch (loopMode) {
  20056. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20057. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20058. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  20059. break;
  20060. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20061. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20062. break;
  20063. }
  20064. return quaternion;
  20065. case Animation.ANIMATIONTYPE_VECTOR3:
  20066. switch (loopMode) {
  20067. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20068. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20069. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  20070. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20071. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20072. }
  20073. case Animation.ANIMATIONTYPE_VECTOR2:
  20074. switch (loopMode) {
  20075. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20076. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20077. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  20078. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20079. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20080. }
  20081. case Animation.ANIMATIONTYPE_COLOR3:
  20082. switch (loopMode) {
  20083. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20084. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20085. return this.color3InterpolateFunction(startValue, endValue, gradient);
  20086. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20087. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20088. }
  20089. case Animation.ANIMATIONTYPE_MATRIX:
  20090. switch (loopMode) {
  20091. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20092. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20093. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20094. return startValue;
  20095. }
  20096. default:
  20097. break;
  20098. }
  20099. break;
  20100. }
  20101. }
  20102. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  20103. };
  20104. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  20105. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  20106. this._stopped = true;
  20107. return false;
  20108. }
  20109. var returnValue = true;
  20110. // Adding a start key at frame 0 if missing
  20111. if (this._keys[0].frame !== 0) {
  20112. var newKey = { frame: 0, value: this._keys[0].value };
  20113. this._keys.splice(0, 0, newKey);
  20114. }
  20115. // Check limits
  20116. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  20117. from = this._keys[0].frame;
  20118. }
  20119. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  20120. to = this._keys[this._keys.length - 1].frame;
  20121. }
  20122. // Compute ratio
  20123. var range = to - from;
  20124. var offsetValue;
  20125. // ratio represents the frame delta between from and to
  20126. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  20127. var highLimitValue = 0;
  20128. if (ratio > range && !loop) {
  20129. returnValue = false;
  20130. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  20131. }
  20132. else {
  20133. // Get max value if required
  20134. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  20135. var keyOffset = to.toString() + from.toString();
  20136. if (!this._offsetsCache[keyOffset]) {
  20137. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20138. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20139. switch (this.dataType) {
  20140. case Animation.ANIMATIONTYPE_FLOAT:
  20141. this._offsetsCache[keyOffset] = toValue - fromValue;
  20142. break;
  20143. case Animation.ANIMATIONTYPE_QUATERNION:
  20144. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20145. break;
  20146. case Animation.ANIMATIONTYPE_VECTOR3:
  20147. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20148. case Animation.ANIMATIONTYPE_VECTOR2:
  20149. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20150. case Animation.ANIMATIONTYPE_COLOR3:
  20151. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20152. default:
  20153. break;
  20154. }
  20155. this._highLimitsCache[keyOffset] = toValue;
  20156. }
  20157. highLimitValue = this._highLimitsCache[keyOffset];
  20158. offsetValue = this._offsetsCache[keyOffset];
  20159. }
  20160. }
  20161. if (offsetValue === undefined) {
  20162. switch (this.dataType) {
  20163. case Animation.ANIMATIONTYPE_FLOAT:
  20164. offsetValue = 0;
  20165. break;
  20166. case Animation.ANIMATIONTYPE_QUATERNION:
  20167. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  20168. break;
  20169. case Animation.ANIMATIONTYPE_VECTOR3:
  20170. offsetValue = BABYLON.Vector3.Zero();
  20171. break;
  20172. case Animation.ANIMATIONTYPE_VECTOR2:
  20173. offsetValue = BABYLON.Vector2.Zero();
  20174. break;
  20175. case Animation.ANIMATIONTYPE_COLOR3:
  20176. offsetValue = BABYLON.Color3.Black();
  20177. }
  20178. }
  20179. // Compute value
  20180. var repeatCount = (ratio / range) >> 0;
  20181. var currentFrame = returnValue ? from + ratio % range : to;
  20182. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  20183. // Set value
  20184. if (this.targetPropertyPath.length > 1) {
  20185. var property = this._target[this.targetPropertyPath[0]];
  20186. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  20187. property = property[this.targetPropertyPath[index]];
  20188. }
  20189. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  20190. }
  20191. else {
  20192. this._target[this.targetPropertyPath[0]] = currentValue;
  20193. }
  20194. if (this._target.markAsDirty) {
  20195. this._target.markAsDirty(this.targetProperty);
  20196. }
  20197. if (!returnValue) {
  20198. this._stopped = true;
  20199. }
  20200. return returnValue;
  20201. };
  20202. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  20203. get: function () {
  20204. return Animation._ANIMATIONTYPE_FLOAT;
  20205. },
  20206. enumerable: true,
  20207. configurable: true
  20208. });
  20209. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  20210. get: function () {
  20211. return Animation._ANIMATIONTYPE_VECTOR3;
  20212. },
  20213. enumerable: true,
  20214. configurable: true
  20215. });
  20216. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  20217. get: function () {
  20218. return Animation._ANIMATIONTYPE_VECTOR2;
  20219. },
  20220. enumerable: true,
  20221. configurable: true
  20222. });
  20223. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  20224. get: function () {
  20225. return Animation._ANIMATIONTYPE_QUATERNION;
  20226. },
  20227. enumerable: true,
  20228. configurable: true
  20229. });
  20230. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  20231. get: function () {
  20232. return Animation._ANIMATIONTYPE_MATRIX;
  20233. },
  20234. enumerable: true,
  20235. configurable: true
  20236. });
  20237. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  20238. get: function () {
  20239. return Animation._ANIMATIONTYPE_COLOR3;
  20240. },
  20241. enumerable: true,
  20242. configurable: true
  20243. });
  20244. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  20245. get: function () {
  20246. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  20247. },
  20248. enumerable: true,
  20249. configurable: true
  20250. });
  20251. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  20252. get: function () {
  20253. return Animation._ANIMATIONLOOPMODE_CYCLE;
  20254. },
  20255. enumerable: true,
  20256. configurable: true
  20257. });
  20258. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  20259. get: function () {
  20260. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  20261. },
  20262. enumerable: true,
  20263. configurable: true
  20264. });
  20265. // Statics
  20266. Animation._ANIMATIONTYPE_FLOAT = 0;
  20267. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  20268. Animation._ANIMATIONTYPE_QUATERNION = 2;
  20269. Animation._ANIMATIONTYPE_MATRIX = 3;
  20270. Animation._ANIMATIONTYPE_COLOR3 = 4;
  20271. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  20272. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  20273. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  20274. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  20275. return Animation;
  20276. })();
  20277. BABYLON.Animation = Animation;
  20278. })(BABYLON || (BABYLON = {}));
  20279. //# sourceMappingURL=babylon.animation.js.map
  20280. var BABYLON;
  20281. (function (BABYLON) {
  20282. var Animatable = (function () {
  20283. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  20284. if (fromFrame === void 0) { fromFrame = 0; }
  20285. if (toFrame === void 0) { toFrame = 100; }
  20286. if (loopAnimation === void 0) { loopAnimation = false; }
  20287. if (speedRatio === void 0) { speedRatio = 1.0; }
  20288. this.target = target;
  20289. this.fromFrame = fromFrame;
  20290. this.toFrame = toFrame;
  20291. this.loopAnimation = loopAnimation;
  20292. this.speedRatio = speedRatio;
  20293. this.onAnimationEnd = onAnimationEnd;
  20294. this._animations = new Array();
  20295. this._paused = false;
  20296. this.animationStarted = false;
  20297. if (animations) {
  20298. this.appendAnimations(target, animations);
  20299. }
  20300. this._scene = scene;
  20301. scene._activeAnimatables.push(this);
  20302. }
  20303. // Methods
  20304. Animatable.prototype.appendAnimations = function (target, animations) {
  20305. for (var index = 0; index < animations.length; index++) {
  20306. var animation = animations[index];
  20307. animation._target = target;
  20308. this._animations.push(animation);
  20309. }
  20310. };
  20311. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  20312. var animations = this._animations;
  20313. for (var index = 0; index < animations.length; index++) {
  20314. if (animations[index].targetProperty === property) {
  20315. return animations[index];
  20316. }
  20317. }
  20318. return null;
  20319. };
  20320. Animatable.prototype.pause = function () {
  20321. if (this._paused) {
  20322. return;
  20323. }
  20324. this._paused = true;
  20325. };
  20326. Animatable.prototype.restart = function () {
  20327. this._paused = false;
  20328. };
  20329. Animatable.prototype.stop = function () {
  20330. var index = this._scene._activeAnimatables.indexOf(this);
  20331. if (index > -1) {
  20332. this._scene._activeAnimatables.splice(index, 1);
  20333. }
  20334. if (this.onAnimationEnd) {
  20335. this.onAnimationEnd();
  20336. }
  20337. };
  20338. Animatable.prototype._animate = function (delay) {
  20339. if (this._paused) {
  20340. if (!this._pausedDelay) {
  20341. this._pausedDelay = delay;
  20342. }
  20343. return true;
  20344. }
  20345. if (!this._localDelayOffset) {
  20346. this._localDelayOffset = delay;
  20347. }
  20348. else if (this._pausedDelay) {
  20349. this._localDelayOffset += delay - this._pausedDelay;
  20350. this._pausedDelay = null;
  20351. }
  20352. // Animating
  20353. var running = false;
  20354. var animations = this._animations;
  20355. for (var index = 0; index < animations.length; index++) {
  20356. var animation = animations[index];
  20357. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  20358. running = running || isRunning;
  20359. }
  20360. if (!running) {
  20361. // Remove from active animatables
  20362. index = this._scene._activeAnimatables.indexOf(this);
  20363. this._scene._activeAnimatables.splice(index, 1);
  20364. }
  20365. if (!running && this.onAnimationEnd) {
  20366. this.onAnimationEnd();
  20367. }
  20368. return running;
  20369. };
  20370. return Animatable;
  20371. })();
  20372. BABYLON.Animatable = Animatable;
  20373. })(BABYLON || (BABYLON = {}));
  20374. //# sourceMappingURL=babylon.animatable.js.map
  20375. var __extends = this.__extends || function (d, b) {
  20376. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  20377. function __() { this.constructor = d; }
  20378. __.prototype = b.prototype;
  20379. d.prototype = new __();
  20380. };
  20381. var BABYLON;
  20382. (function (BABYLON) {
  20383. var EasingFunction = (function () {
  20384. function EasingFunction() {
  20385. // Properties
  20386. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  20387. }
  20388. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  20389. get: function () {
  20390. return EasingFunction._EASINGMODE_EASEIN;
  20391. },
  20392. enumerable: true,
  20393. configurable: true
  20394. });
  20395. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  20396. get: function () {
  20397. return EasingFunction._EASINGMODE_EASEOUT;
  20398. },
  20399. enumerable: true,
  20400. configurable: true
  20401. });
  20402. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  20403. get: function () {
  20404. return EasingFunction._EASINGMODE_EASEINOUT;
  20405. },
  20406. enumerable: true,
  20407. configurable: true
  20408. });
  20409. EasingFunction.prototype.setEasingMode = function (easingMode) {
  20410. var n = Math.min(Math.max(easingMode, 0), 2);
  20411. this._easingMode = n;
  20412. };
  20413. EasingFunction.prototype.getEasingMode = function () {
  20414. return this._easingMode;
  20415. };
  20416. EasingFunction.prototype.easeInCore = function (gradient) {
  20417. throw new Error('You must implement this method');
  20418. };
  20419. EasingFunction.prototype.ease = function (gradient) {
  20420. switch (this._easingMode) {
  20421. case EasingFunction.EASINGMODE_EASEIN:
  20422. return this.easeInCore(gradient);
  20423. case EasingFunction.EASINGMODE_EASEOUT:
  20424. return (1 - this.easeInCore(1 - gradient));
  20425. }
  20426. if (gradient >= 0.5) {
  20427. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  20428. }
  20429. return (this.easeInCore(gradient * 2) * 0.5);
  20430. };
  20431. //Statics
  20432. EasingFunction._EASINGMODE_EASEIN = 0;
  20433. EasingFunction._EASINGMODE_EASEOUT = 1;
  20434. EasingFunction._EASINGMODE_EASEINOUT = 2;
  20435. return EasingFunction;
  20436. })();
  20437. BABYLON.EasingFunction = EasingFunction;
  20438. var CircleEase = (function (_super) {
  20439. __extends(CircleEase, _super);
  20440. function CircleEase() {
  20441. _super.apply(this, arguments);
  20442. }
  20443. CircleEase.prototype.easeInCore = function (gradient) {
  20444. gradient = Math.max(0, Math.min(1, gradient));
  20445. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  20446. };
  20447. return CircleEase;
  20448. })(EasingFunction);
  20449. BABYLON.CircleEase = CircleEase;
  20450. var BackEase = (function (_super) {
  20451. __extends(BackEase, _super);
  20452. function BackEase(amplitude) {
  20453. if (amplitude === void 0) { amplitude = 1; }
  20454. _super.call(this);
  20455. this.amplitude = amplitude;
  20456. }
  20457. BackEase.prototype.easeInCore = function (gradient) {
  20458. var num = Math.max(0, this.amplitude);
  20459. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  20460. };
  20461. return BackEase;
  20462. })(EasingFunction);
  20463. BABYLON.BackEase = BackEase;
  20464. var BounceEase = (function (_super) {
  20465. __extends(BounceEase, _super);
  20466. function BounceEase(bounces, bounciness) {
  20467. if (bounces === void 0) { bounces = 3; }
  20468. if (bounciness === void 0) { bounciness = 2; }
  20469. _super.call(this);
  20470. this.bounces = bounces;
  20471. this.bounciness = bounciness;
  20472. }
  20473. BounceEase.prototype.easeInCore = function (gradient) {
  20474. var y = Math.max(0.0, this.bounces);
  20475. var bounciness = this.bounciness;
  20476. if (bounciness <= 1.0) {
  20477. bounciness = 1.001;
  20478. }
  20479. var num9 = Math.pow(bounciness, y);
  20480. var num5 = 1.0 - bounciness;
  20481. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  20482. var num15 = gradient * num4;
  20483. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  20484. var num3 = Math.floor(num65);
  20485. var num13 = num3 + 1.0;
  20486. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  20487. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  20488. var num7 = (num8 + num12) * 0.5;
  20489. var num6 = gradient - num7;
  20490. var num2 = num7 - num8;
  20491. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  20492. };
  20493. return BounceEase;
  20494. })(EasingFunction);
  20495. BABYLON.BounceEase = BounceEase;
  20496. var CubicEase = (function (_super) {
  20497. __extends(CubicEase, _super);
  20498. function CubicEase() {
  20499. _super.apply(this, arguments);
  20500. }
  20501. CubicEase.prototype.easeInCore = function (gradient) {
  20502. return (gradient * gradient * gradient);
  20503. };
  20504. return CubicEase;
  20505. })(EasingFunction);
  20506. BABYLON.CubicEase = CubicEase;
  20507. var ElasticEase = (function (_super) {
  20508. __extends(ElasticEase, _super);
  20509. function ElasticEase(oscillations, springiness) {
  20510. if (oscillations === void 0) { oscillations = 3; }
  20511. if (springiness === void 0) { springiness = 3; }
  20512. _super.call(this);
  20513. this.oscillations = oscillations;
  20514. this.springiness = springiness;
  20515. }
  20516. ElasticEase.prototype.easeInCore = function (gradient) {
  20517. var num2;
  20518. var num3 = Math.max(0.0, this.oscillations);
  20519. var num = Math.max(0.0, this.springiness);
  20520. if (num == 0) {
  20521. num2 = gradient;
  20522. }
  20523. else {
  20524. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  20525. }
  20526. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  20527. };
  20528. return ElasticEase;
  20529. })(EasingFunction);
  20530. BABYLON.ElasticEase = ElasticEase;
  20531. var ExponentialEase = (function (_super) {
  20532. __extends(ExponentialEase, _super);
  20533. function ExponentialEase(exponent) {
  20534. if (exponent === void 0) { exponent = 2; }
  20535. _super.call(this);
  20536. this.exponent = exponent;
  20537. }
  20538. ExponentialEase.prototype.easeInCore = function (gradient) {
  20539. if (this.exponent <= 0) {
  20540. return gradient;
  20541. }
  20542. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  20543. };
  20544. return ExponentialEase;
  20545. })(EasingFunction);
  20546. BABYLON.ExponentialEase = ExponentialEase;
  20547. var PowerEase = (function (_super) {
  20548. __extends(PowerEase, _super);
  20549. function PowerEase(power) {
  20550. if (power === void 0) { power = 2; }
  20551. _super.call(this);
  20552. this.power = power;
  20553. }
  20554. PowerEase.prototype.easeInCore = function (gradient) {
  20555. var y = Math.max(0.0, this.power);
  20556. return Math.pow(gradient, y);
  20557. };
  20558. return PowerEase;
  20559. })(EasingFunction);
  20560. BABYLON.PowerEase = PowerEase;
  20561. var QuadraticEase = (function (_super) {
  20562. __extends(QuadraticEase, _super);
  20563. function QuadraticEase() {
  20564. _super.apply(this, arguments);
  20565. }
  20566. QuadraticEase.prototype.easeInCore = function (gradient) {
  20567. return (gradient * gradient);
  20568. };
  20569. return QuadraticEase;
  20570. })(EasingFunction);
  20571. BABYLON.QuadraticEase = QuadraticEase;
  20572. var QuarticEase = (function (_super) {
  20573. __extends(QuarticEase, _super);
  20574. function QuarticEase() {
  20575. _super.apply(this, arguments);
  20576. }
  20577. QuarticEase.prototype.easeInCore = function (gradient) {
  20578. return (gradient * gradient * gradient * gradient);
  20579. };
  20580. return QuarticEase;
  20581. })(EasingFunction);
  20582. BABYLON.QuarticEase = QuarticEase;
  20583. var QuinticEase = (function (_super) {
  20584. __extends(QuinticEase, _super);
  20585. function QuinticEase() {
  20586. _super.apply(this, arguments);
  20587. }
  20588. QuinticEase.prototype.easeInCore = function (gradient) {
  20589. return (gradient * gradient * gradient * gradient * gradient);
  20590. };
  20591. return QuinticEase;
  20592. })(EasingFunction);
  20593. BABYLON.QuinticEase = QuinticEase;
  20594. var SineEase = (function (_super) {
  20595. __extends(SineEase, _super);
  20596. function SineEase() {
  20597. _super.apply(this, arguments);
  20598. }
  20599. SineEase.prototype.easeInCore = function (gradient) {
  20600. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  20601. };
  20602. return SineEase;
  20603. })(EasingFunction);
  20604. BABYLON.SineEase = SineEase;
  20605. var BezierCurveEase = (function (_super) {
  20606. __extends(BezierCurveEase, _super);
  20607. function BezierCurveEase(x1, y1, x2, y2) {
  20608. if (x1 === void 0) { x1 = 0; }
  20609. if (y1 === void 0) { y1 = 0; }
  20610. if (x2 === void 0) { x2 = 1; }
  20611. if (y2 === void 0) { y2 = 1; }
  20612. _super.call(this);
  20613. this.x1 = x1;
  20614. this.y1 = y1;
  20615. this.x2 = x2;
  20616. this.y2 = y2;
  20617. }
  20618. BezierCurveEase.prototype.easeInCore = function (gradient) {
  20619. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  20620. };
  20621. return BezierCurveEase;
  20622. })(EasingFunction);
  20623. BABYLON.BezierCurveEase = BezierCurveEase;
  20624. })(BABYLON || (BABYLON = {}));
  20625. //# sourceMappingURL=babylon.easing.js.map
  20626. var BABYLON;
  20627. (function (BABYLON) {
  20628. var Octree = (function () {
  20629. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  20630. if (maxDepth === void 0) { maxDepth = 2; }
  20631. this.maxDepth = maxDepth;
  20632. this.dynamicContent = new Array();
  20633. this._maxBlockCapacity = maxBlockCapacity || 64;
  20634. this._selectionContent = new BABYLON.SmartArray(1024);
  20635. this._creationFunc = creationFunc;
  20636. }
  20637. // Methods
  20638. Octree.prototype.update = function (worldMin, worldMax, entries) {
  20639. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  20640. };
  20641. Octree.prototype.addMesh = function (entry) {
  20642. for (var index = 0; index < this.blocks.length; index++) {
  20643. var block = this.blocks[index];
  20644. block.addEntry(entry);
  20645. }
  20646. };
  20647. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  20648. this._selectionContent.reset();
  20649. for (var index = 0; index < this.blocks.length; index++) {
  20650. var block = this.blocks[index];
  20651. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  20652. }
  20653. if (allowDuplicate) {
  20654. this._selectionContent.concat(this.dynamicContent);
  20655. }
  20656. else {
  20657. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20658. }
  20659. return this._selectionContent;
  20660. };
  20661. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  20662. this._selectionContent.reset();
  20663. for (var index = 0; index < this.blocks.length; index++) {
  20664. var block = this.blocks[index];
  20665. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  20666. }
  20667. if (allowDuplicate) {
  20668. this._selectionContent.concat(this.dynamicContent);
  20669. }
  20670. else {
  20671. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20672. }
  20673. return this._selectionContent;
  20674. };
  20675. Octree.prototype.intersectsRay = function (ray) {
  20676. this._selectionContent.reset();
  20677. for (var index = 0; index < this.blocks.length; index++) {
  20678. var block = this.blocks[index];
  20679. block.intersectsRay(ray, this._selectionContent);
  20680. }
  20681. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  20682. return this._selectionContent;
  20683. };
  20684. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  20685. target.blocks = new Array();
  20686. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  20687. for (var x = 0; x < 2; x++) {
  20688. for (var y = 0; y < 2; y++) {
  20689. for (var z = 0; z < 2; z++) {
  20690. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  20691. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  20692. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  20693. block.addEntries(entries);
  20694. target.blocks.push(block);
  20695. }
  20696. }
  20697. }
  20698. };
  20699. Octree.CreationFuncForMeshes = function (entry, block) {
  20700. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  20701. block.entries.push(entry);
  20702. }
  20703. };
  20704. Octree.CreationFuncForSubMeshes = function (entry, block) {
  20705. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  20706. block.entries.push(entry);
  20707. }
  20708. };
  20709. return Octree;
  20710. })();
  20711. BABYLON.Octree = Octree;
  20712. })(BABYLON || (BABYLON = {}));
  20713. //# sourceMappingURL=babylon.octree.js.map
  20714. var BABYLON;
  20715. (function (BABYLON) {
  20716. var OctreeBlock = (function () {
  20717. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  20718. this.entries = new Array();
  20719. this._boundingVectors = new Array();
  20720. this._capacity = capacity;
  20721. this._depth = depth;
  20722. this._maxDepth = maxDepth;
  20723. this._creationFunc = creationFunc;
  20724. this._minPoint = minPoint;
  20725. this._maxPoint = maxPoint;
  20726. this._boundingVectors.push(minPoint.clone());
  20727. this._boundingVectors.push(maxPoint.clone());
  20728. this._boundingVectors.push(minPoint.clone());
  20729. this._boundingVectors[2].x = maxPoint.x;
  20730. this._boundingVectors.push(minPoint.clone());
  20731. this._boundingVectors[3].y = maxPoint.y;
  20732. this._boundingVectors.push(minPoint.clone());
  20733. this._boundingVectors[4].z = maxPoint.z;
  20734. this._boundingVectors.push(maxPoint.clone());
  20735. this._boundingVectors[5].z = minPoint.z;
  20736. this._boundingVectors.push(maxPoint.clone());
  20737. this._boundingVectors[6].x = minPoint.x;
  20738. this._boundingVectors.push(maxPoint.clone());
  20739. this._boundingVectors[7].y = minPoint.y;
  20740. }
  20741. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  20742. // Property
  20743. get: function () {
  20744. return this._capacity;
  20745. },
  20746. enumerable: true,
  20747. configurable: true
  20748. });
  20749. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  20750. get: function () {
  20751. return this._minPoint;
  20752. },
  20753. enumerable: true,
  20754. configurable: true
  20755. });
  20756. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  20757. get: function () {
  20758. return this._maxPoint;
  20759. },
  20760. enumerable: true,
  20761. configurable: true
  20762. });
  20763. // Methods
  20764. OctreeBlock.prototype.addEntry = function (entry) {
  20765. if (this.blocks) {
  20766. for (var index = 0; index < this.blocks.length; index++) {
  20767. var block = this.blocks[index];
  20768. block.addEntry(entry);
  20769. }
  20770. return;
  20771. }
  20772. this._creationFunc(entry, this);
  20773. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  20774. this.createInnerBlocks();
  20775. }
  20776. };
  20777. OctreeBlock.prototype.addEntries = function (entries) {
  20778. for (var index = 0; index < entries.length; index++) {
  20779. var mesh = entries[index];
  20780. this.addEntry(mesh);
  20781. }
  20782. };
  20783. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  20784. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  20785. if (this.blocks) {
  20786. for (var index = 0; index < this.blocks.length; index++) {
  20787. var block = this.blocks[index];
  20788. block.select(frustumPlanes, selection, allowDuplicate);
  20789. }
  20790. return;
  20791. }
  20792. if (allowDuplicate) {
  20793. selection.concat(this.entries);
  20794. }
  20795. else {
  20796. selection.concatWithNoDuplicate(this.entries);
  20797. }
  20798. }
  20799. };
  20800. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  20801. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  20802. if (this.blocks) {
  20803. for (var index = 0; index < this.blocks.length; index++) {
  20804. var block = this.blocks[index];
  20805. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  20806. }
  20807. return;
  20808. }
  20809. if (allowDuplicate) {
  20810. selection.concat(this.entries);
  20811. }
  20812. else {
  20813. selection.concatWithNoDuplicate(this.entries);
  20814. }
  20815. }
  20816. };
  20817. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  20818. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  20819. if (this.blocks) {
  20820. for (var index = 0; index < this.blocks.length; index++) {
  20821. var block = this.blocks[index];
  20822. block.intersectsRay(ray, selection);
  20823. }
  20824. return;
  20825. }
  20826. selection.concatWithNoDuplicate(this.entries);
  20827. }
  20828. };
  20829. OctreeBlock.prototype.createInnerBlocks = function () {
  20830. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  20831. };
  20832. return OctreeBlock;
  20833. })();
  20834. BABYLON.OctreeBlock = OctreeBlock;
  20835. })(BABYLON || (BABYLON = {}));
  20836. //# sourceMappingURL=babylon.octreeBlock.js.map
  20837. var BABYLON;
  20838. (function (BABYLON) {
  20839. var Bone = (function () {
  20840. function Bone(name, skeleton, parentBone, matrix) {
  20841. this.name = name;
  20842. this.children = new Array();
  20843. this.animations = new Array();
  20844. this._worldTransform = new BABYLON.Matrix();
  20845. this._absoluteTransform = new BABYLON.Matrix();
  20846. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  20847. this._skeleton = skeleton;
  20848. this._matrix = matrix;
  20849. this._baseMatrix = matrix;
  20850. skeleton.bones.push(this);
  20851. if (parentBone) {
  20852. this._parent = parentBone;
  20853. parentBone.children.push(this);
  20854. }
  20855. else {
  20856. this._parent = null;
  20857. }
  20858. this._updateDifferenceMatrix();
  20859. }
  20860. // Members
  20861. Bone.prototype.getParent = function () {
  20862. return this._parent;
  20863. };
  20864. Bone.prototype.getLocalMatrix = function () {
  20865. return this._matrix;
  20866. };
  20867. Bone.prototype.getBaseMatrix = function () {
  20868. return this._baseMatrix;
  20869. };
  20870. Bone.prototype.getWorldMatrix = function () {
  20871. return this._worldTransform;
  20872. };
  20873. Bone.prototype.getInvertedAbsoluteTransform = function () {
  20874. return this._invertedAbsoluteTransform;
  20875. };
  20876. Bone.prototype.getAbsoluteMatrix = function () {
  20877. var matrix = this._matrix.clone();
  20878. var parent = this._parent;
  20879. while (parent) {
  20880. matrix = matrix.multiply(parent.getLocalMatrix());
  20881. parent = parent.getParent();
  20882. }
  20883. return matrix;
  20884. };
  20885. // Methods
  20886. Bone.prototype.updateMatrix = function (matrix) {
  20887. this._matrix = matrix;
  20888. this._skeleton._markAsDirty();
  20889. this._updateDifferenceMatrix();
  20890. };
  20891. Bone.prototype._updateDifferenceMatrix = function () {
  20892. if (this._parent) {
  20893. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  20894. }
  20895. else {
  20896. this._absoluteTransform.copyFrom(this._matrix);
  20897. }
  20898. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  20899. for (var index = 0; index < this.children.length; index++) {
  20900. this.children[index]._updateDifferenceMatrix();
  20901. }
  20902. };
  20903. Bone.prototype.markAsDirty = function () {
  20904. this._skeleton._markAsDirty();
  20905. };
  20906. return Bone;
  20907. })();
  20908. BABYLON.Bone = Bone;
  20909. })(BABYLON || (BABYLON = {}));
  20910. //# sourceMappingURL=babylon.bone.js.map
  20911. var BABYLON;
  20912. (function (BABYLON) {
  20913. var Skeleton = (function () {
  20914. function Skeleton(name, id, scene) {
  20915. this.name = name;
  20916. this.id = id;
  20917. this.bones = new Array();
  20918. this._isDirty = true;
  20919. this._identity = BABYLON.Matrix.Identity();
  20920. this.bones = [];
  20921. this._scene = scene;
  20922. scene.skeletons.push(this);
  20923. this.prepare();
  20924. //make sure it will recalculate the matrix next time prepare is called.
  20925. this._isDirty = true;
  20926. }
  20927. // Members
  20928. Skeleton.prototype.getTransformMatrices = function () {
  20929. return this._transformMatrices;
  20930. };
  20931. // Methods
  20932. Skeleton.prototype._markAsDirty = function () {
  20933. this._isDirty = true;
  20934. };
  20935. Skeleton.prototype.prepare = function () {
  20936. if (!this._isDirty) {
  20937. return;
  20938. }
  20939. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  20940. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  20941. }
  20942. for (var index = 0; index < this.bones.length; index++) {
  20943. var bone = this.bones[index];
  20944. var parentBone = bone.getParent();
  20945. if (parentBone) {
  20946. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  20947. }
  20948. else {
  20949. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  20950. }
  20951. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  20952. }
  20953. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  20954. this._isDirty = false;
  20955. this._scene._activeBones += this.bones.length;
  20956. };
  20957. Skeleton.prototype.getAnimatables = function () {
  20958. if (!this._animatables || this._animatables.length !== this.bones.length) {
  20959. this._animatables = [];
  20960. for (var index = 0; index < this.bones.length; index++) {
  20961. this._animatables.push(this.bones[index]);
  20962. }
  20963. }
  20964. return this._animatables;
  20965. };
  20966. Skeleton.prototype.clone = function (name, id) {
  20967. var result = new Skeleton(name, id || name, this._scene);
  20968. for (var index = 0; index < this.bones.length; index++) {
  20969. var source = this.bones[index];
  20970. var parentBone = null;
  20971. if (source.getParent()) {
  20972. var parentIndex = this.bones.indexOf(source.getParent());
  20973. parentBone = result.bones[parentIndex];
  20974. }
  20975. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  20976. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  20977. }
  20978. return result;
  20979. };
  20980. return Skeleton;
  20981. })();
  20982. BABYLON.Skeleton = Skeleton;
  20983. })(BABYLON || (BABYLON = {}));
  20984. //# sourceMappingURL=babylon.skeleton.js.map
  20985. var BABYLON;
  20986. (function (BABYLON) {
  20987. var PostProcess = (function () {
  20988. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  20989. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  20990. this.name = name;
  20991. this.width = -1;
  20992. this.height = -1;
  20993. this._reusable = false;
  20994. this._textures = new BABYLON.SmartArray(2);
  20995. this._currentRenderTextureInd = 0;
  20996. if (camera != null) {
  20997. this._camera = camera;
  20998. this._scene = camera.getScene();
  20999. camera.attachPostProcess(this);
  21000. this._engine = this._scene.getEngine();
  21001. }
  21002. else {
  21003. this._engine = engine;
  21004. }
  21005. this._renderRatio = ratio;
  21006. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  21007. this._reusable = reusable || false;
  21008. samplers = samplers || [];
  21009. samplers.push("textureSampler");
  21010. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  21011. }
  21012. PostProcess.prototype.isReusable = function () {
  21013. return this._reusable;
  21014. };
  21015. PostProcess.prototype.activate = function (camera, sourceTexture) {
  21016. camera = camera || this._camera;
  21017. var scene = camera.getScene();
  21018. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  21019. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  21020. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  21021. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  21022. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  21023. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  21024. if (this._textures.length > 0) {
  21025. for (var i = 0; i < this._textures.length; i++) {
  21026. this._engine._releaseTexture(this._textures.data[i]);
  21027. }
  21028. this._textures.reset();
  21029. }
  21030. this.width = desiredWidth;
  21031. this.height = desiredHeight;
  21032. 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 }));
  21033. if (this._reusable) {
  21034. 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 }));
  21035. }
  21036. if (this.onSizeChanged) {
  21037. this.onSizeChanged();
  21038. }
  21039. }
  21040. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  21041. if (this.onActivate) {
  21042. this.onActivate(camera);
  21043. }
  21044. // Clear
  21045. if (this.clearColor) {
  21046. this._engine.clear(this.clearColor, true, true);
  21047. }
  21048. else {
  21049. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  21050. }
  21051. if (this._reusable) {
  21052. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  21053. }
  21054. };
  21055. PostProcess.prototype.apply = function () {
  21056. // Check
  21057. if (!this._effect.isReady())
  21058. return null;
  21059. // States
  21060. this._engine.enableEffect(this._effect);
  21061. this._engine.setState(false);
  21062. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21063. this._engine.setDepthBuffer(false);
  21064. this._engine.setDepthWrite(false);
  21065. // Texture
  21066. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  21067. // Parameters
  21068. if (this.onApply) {
  21069. this.onApply(this._effect);
  21070. }
  21071. return this._effect;
  21072. };
  21073. PostProcess.prototype.dispose = function (camera) {
  21074. camera = camera || this._camera;
  21075. if (this._textures.length > 0) {
  21076. for (var i = 0; i < this._textures.length; i++) {
  21077. this._engine._releaseTexture(this._textures.data[i]);
  21078. }
  21079. this._textures.reset();
  21080. }
  21081. if (!camera) {
  21082. return;
  21083. }
  21084. camera.detachPostProcess(this);
  21085. var index = camera._postProcesses.indexOf(this);
  21086. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  21087. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  21088. }
  21089. };
  21090. return PostProcess;
  21091. })();
  21092. BABYLON.PostProcess = PostProcess;
  21093. })(BABYLON || (BABYLON = {}));
  21094. //# sourceMappingURL=babylon.postProcess.js.map
  21095. var BABYLON;
  21096. (function (BABYLON) {
  21097. var PostProcessManager = (function () {
  21098. function PostProcessManager(scene) {
  21099. this._vertexDeclaration = [2];
  21100. this._vertexStrideSize = 2 * 4;
  21101. this._scene = scene;
  21102. }
  21103. PostProcessManager.prototype._prepareBuffers = function () {
  21104. if (this._vertexBuffer) {
  21105. return;
  21106. }
  21107. // VBO
  21108. var vertices = [];
  21109. vertices.push(1, 1);
  21110. vertices.push(-1, 1);
  21111. vertices.push(-1, -1);
  21112. vertices.push(1, -1);
  21113. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  21114. // Indices
  21115. var indices = [];
  21116. indices.push(0);
  21117. indices.push(1);
  21118. indices.push(2);
  21119. indices.push(0);
  21120. indices.push(2);
  21121. indices.push(3);
  21122. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  21123. };
  21124. // Methods
  21125. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  21126. var postProcesses = this._scene.activeCamera._postProcesses;
  21127. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21128. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21129. return false;
  21130. }
  21131. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  21132. return true;
  21133. };
  21134. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  21135. var engine = this._scene.getEngine();
  21136. for (var index = 0; index < postProcesses.length; index++) {
  21137. if (index < postProcesses.length - 1) {
  21138. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  21139. }
  21140. else {
  21141. if (targetTexture) {
  21142. engine.bindFramebuffer(targetTexture);
  21143. }
  21144. else {
  21145. engine.restoreDefaultFramebuffer();
  21146. }
  21147. }
  21148. var pp = postProcesses[index];
  21149. var effect = pp.apply();
  21150. if (effect) {
  21151. if (pp.onBeforeRender) {
  21152. pp.onBeforeRender(effect);
  21153. }
  21154. // VBOs
  21155. this._prepareBuffers();
  21156. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21157. // Draw order
  21158. engine.draw(true, 0, 6);
  21159. }
  21160. }
  21161. // Restore depth buffer
  21162. engine.setDepthBuffer(true);
  21163. engine.setDepthWrite(true);
  21164. };
  21165. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  21166. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  21167. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21168. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21169. return;
  21170. }
  21171. var engine = this._scene.getEngine();
  21172. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  21173. if (index < postProcessesTakenIndices.length - 1) {
  21174. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  21175. }
  21176. else {
  21177. if (targetTexture) {
  21178. engine.bindFramebuffer(targetTexture);
  21179. }
  21180. else {
  21181. engine.restoreDefaultFramebuffer();
  21182. }
  21183. }
  21184. if (doNotPresent) {
  21185. break;
  21186. }
  21187. var pp = postProcesses[postProcessesTakenIndices[index]];
  21188. var effect = pp.apply();
  21189. if (effect) {
  21190. if (pp.onBeforeRender) {
  21191. pp.onBeforeRender(effect);
  21192. }
  21193. // VBOs
  21194. this._prepareBuffers();
  21195. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21196. // Draw order
  21197. engine.draw(true, 0, 6);
  21198. }
  21199. }
  21200. // Restore depth buffer
  21201. engine.setDepthBuffer(true);
  21202. engine.setDepthWrite(true);
  21203. };
  21204. PostProcessManager.prototype.dispose = function () {
  21205. if (this._vertexBuffer) {
  21206. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21207. this._vertexBuffer = null;
  21208. }
  21209. if (this._indexBuffer) {
  21210. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21211. this._indexBuffer = null;
  21212. }
  21213. };
  21214. return PostProcessManager;
  21215. })();
  21216. BABYLON.PostProcessManager = PostProcessManager;
  21217. })(BABYLON || (BABYLON = {}));
  21218. //# sourceMappingURL=babylon.postProcessManager.js.map
  21219. var __extends = this.__extends || function (d, b) {
  21220. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21221. function __() { this.constructor = d; }
  21222. __.prototype = b.prototype;
  21223. d.prototype = new __();
  21224. };
  21225. var BABYLON;
  21226. (function (BABYLON) {
  21227. var PassPostProcess = (function (_super) {
  21228. __extends(PassPostProcess, _super);
  21229. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21230. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  21231. }
  21232. return PassPostProcess;
  21233. })(BABYLON.PostProcess);
  21234. BABYLON.PassPostProcess = PassPostProcess;
  21235. })(BABYLON || (BABYLON = {}));
  21236. //# sourceMappingURL=babylon.passPostProcess.js.map
  21237. var __extends = this.__extends || function (d, b) {
  21238. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21239. function __() { this.constructor = d; }
  21240. __.prototype = b.prototype;
  21241. d.prototype = new __();
  21242. };
  21243. var BABYLON;
  21244. (function (BABYLON) {
  21245. var BlurPostProcess = (function (_super) {
  21246. __extends(BlurPostProcess, _super);
  21247. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  21248. var _this = this;
  21249. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  21250. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  21251. this.direction = direction;
  21252. this.blurWidth = blurWidth;
  21253. this.onApply = function (effect) {
  21254. effect.setFloat2("screenSize", _this.width, _this.height);
  21255. effect.setVector2("direction", _this.direction);
  21256. effect.setFloat("blurWidth", _this.blurWidth);
  21257. };
  21258. }
  21259. return BlurPostProcess;
  21260. })(BABYLON.PostProcess);
  21261. BABYLON.BlurPostProcess = BlurPostProcess;
  21262. })(BABYLON || (BABYLON = {}));
  21263. //# sourceMappingURL=babylon.blurPostProcess.js.map
  21264. var __extends = this.__extends || function (d, b) {
  21265. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21266. function __() { this.constructor = d; }
  21267. __.prototype = b.prototype;
  21268. d.prototype = new __();
  21269. };
  21270. var BABYLON;
  21271. (function (BABYLON) {
  21272. var RefractionPostProcess = (function (_super) {
  21273. __extends(RefractionPostProcess, _super);
  21274. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  21275. var _this = this;
  21276. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  21277. this.color = color;
  21278. this.depth = depth;
  21279. this.colorLevel = colorLevel;
  21280. this.onActivate = function (cam) {
  21281. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  21282. };
  21283. this.onApply = function (effect) {
  21284. effect.setColor3("baseColor", _this.color);
  21285. effect.setFloat("depth", _this.depth);
  21286. effect.setFloat("colorLevel", _this.colorLevel);
  21287. effect.setTexture("refractionSampler", _this._refRexture);
  21288. };
  21289. }
  21290. // Methods
  21291. RefractionPostProcess.prototype.dispose = function (camera) {
  21292. if (this._refRexture) {
  21293. this._refRexture.dispose();
  21294. }
  21295. _super.prototype.dispose.call(this, camera);
  21296. };
  21297. return RefractionPostProcess;
  21298. })(BABYLON.PostProcess);
  21299. BABYLON.RefractionPostProcess = RefractionPostProcess;
  21300. })(BABYLON || (BABYLON = {}));
  21301. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  21302. var __extends = this.__extends || function (d, b) {
  21303. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21304. function __() { this.constructor = d; }
  21305. __.prototype = b.prototype;
  21306. d.prototype = new __();
  21307. };
  21308. var BABYLON;
  21309. (function (BABYLON) {
  21310. var BlackAndWhitePostProcess = (function (_super) {
  21311. __extends(BlackAndWhitePostProcess, _super);
  21312. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21313. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  21314. }
  21315. return BlackAndWhitePostProcess;
  21316. })(BABYLON.PostProcess);
  21317. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  21318. })(BABYLON || (BABYLON = {}));
  21319. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  21320. var __extends = this.__extends || function (d, b) {
  21321. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21322. function __() { this.constructor = d; }
  21323. __.prototype = b.prototype;
  21324. d.prototype = new __();
  21325. };
  21326. var BABYLON;
  21327. (function (BABYLON) {
  21328. var ConvolutionPostProcess = (function (_super) {
  21329. __extends(ConvolutionPostProcess, _super);
  21330. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  21331. var _this = this;
  21332. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  21333. this.kernel = kernel;
  21334. this.onApply = function (effect) {
  21335. effect.setFloat2("screenSize", _this.width, _this.height);
  21336. effect.setArray("kernel", _this.kernel);
  21337. };
  21338. }
  21339. // Statics
  21340. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  21341. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  21342. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  21343. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  21344. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  21345. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  21346. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  21347. return ConvolutionPostProcess;
  21348. })(BABYLON.PostProcess);
  21349. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  21350. })(BABYLON || (BABYLON = {}));
  21351. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  21352. var __extends = this.__extends || function (d, b) {
  21353. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21354. function __() { this.constructor = d; }
  21355. __.prototype = b.prototype;
  21356. d.prototype = new __();
  21357. };
  21358. var BABYLON;
  21359. (function (BABYLON) {
  21360. var FilterPostProcess = (function (_super) {
  21361. __extends(FilterPostProcess, _super);
  21362. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  21363. var _this = this;
  21364. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  21365. this.kernelMatrix = kernelMatrix;
  21366. this.onApply = function (effect) {
  21367. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  21368. };
  21369. }
  21370. return FilterPostProcess;
  21371. })(BABYLON.PostProcess);
  21372. BABYLON.FilterPostProcess = FilterPostProcess;
  21373. })(BABYLON || (BABYLON = {}));
  21374. //# sourceMappingURL=babylon.filterPostProcess.js.map
  21375. var __extends = this.__extends || function (d, b) {
  21376. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21377. function __() { this.constructor = d; }
  21378. __.prototype = b.prototype;
  21379. d.prototype = new __();
  21380. };
  21381. var BABYLON;
  21382. (function (BABYLON) {
  21383. var FxaaPostProcess = (function (_super) {
  21384. __extends(FxaaPostProcess, _super);
  21385. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21386. var _this = this;
  21387. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  21388. this.onSizeChanged = function () {
  21389. _this.texelWidth = 1.0 / _this.width;
  21390. _this.texelHeight = 1.0 / _this.height;
  21391. };
  21392. this.onApply = function (effect) {
  21393. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  21394. };
  21395. }
  21396. return FxaaPostProcess;
  21397. })(BABYLON.PostProcess);
  21398. BABYLON.FxaaPostProcess = FxaaPostProcess;
  21399. })(BABYLON || (BABYLON = {}));
  21400. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  21401. var __extends = this.__extends || function (d, b) {
  21402. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  21403. function __() { this.constructor = d; }
  21404. __.prototype = b.prototype;
  21405. d.prototype = new __();
  21406. };
  21407. var BABYLON;
  21408. (function (BABYLON) {
  21409. var StereogramInterlacePostProcess = (function (_super) {
  21410. __extends(StereogramInterlacePostProcess, _super);
  21411. function StereogramInterlacePostProcess(name, camB, postProcessA, isStereogramHoriz, samplingMode) {
  21412. var _this = this;
  21413. _super.call(this, name, "stereogramInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereogramHoriz ? "#define IS_STEREOGRAM_HORIZ 1" : undefined);
  21414. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  21415. this.onSizeChanged = function () {
  21416. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  21417. };
  21418. this.onApply = function (effect) {
  21419. effect.setTextureFromPostProcess("camASampler", postProcessA);
  21420. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  21421. };
  21422. }
  21423. return StereogramInterlacePostProcess;
  21424. })(BABYLON.PostProcess);
  21425. BABYLON.StereogramInterlacePostProcess = StereogramInterlacePostProcess;
  21426. })(BABYLON || (BABYLON = {}));
  21427. //# sourceMappingURL=babylon.stereogramInterlacePostProcess.js.map
  21428. var BABYLON;
  21429. (function (BABYLON) {
  21430. var LensFlare = (function () {
  21431. function LensFlare(size, position, color, imgUrl, system) {
  21432. this.size = size;
  21433. this.position = position;
  21434. this.dispose = function () {
  21435. if (this.texture) {
  21436. this.texture.dispose();
  21437. }
  21438. // Remove from scene
  21439. var index = this._system.lensFlares.indexOf(this);
  21440. this._system.lensFlares.splice(index, 1);
  21441. };
  21442. this.color = color || new BABYLON.Color3(1, 1, 1);
  21443. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  21444. this._system = system;
  21445. system.lensFlares.push(this);
  21446. }
  21447. return LensFlare;
  21448. })();
  21449. BABYLON.LensFlare = LensFlare;
  21450. })(BABYLON || (BABYLON = {}));
  21451. //# sourceMappingURL=babylon.lensFlare.js.map
  21452. var BABYLON;
  21453. (function (BABYLON) {
  21454. var LensFlareSystem = (function () {
  21455. function LensFlareSystem(name, emitter, scene) {
  21456. this.name = name;
  21457. this.lensFlares = new Array();
  21458. this.borderLimit = 300;
  21459. this._vertexDeclaration = [2];
  21460. this._vertexStrideSize = 2 * 4;
  21461. this._isEnabled = true;
  21462. this._scene = scene;
  21463. this._emitter = emitter;
  21464. scene.lensFlareSystems.push(this);
  21465. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  21466. // VBO
  21467. var vertices = [];
  21468. vertices.push(1, 1);
  21469. vertices.push(-1, 1);
  21470. vertices.push(-1, -1);
  21471. vertices.push(1, -1);
  21472. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21473. // Indices
  21474. var indices = [];
  21475. indices.push(0);
  21476. indices.push(1);
  21477. indices.push(2);
  21478. indices.push(0);
  21479. indices.push(2);
  21480. indices.push(3);
  21481. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21482. // Effects
  21483. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  21484. }
  21485. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  21486. get: function () {
  21487. return this._isEnabled;
  21488. },
  21489. set: function (value) {
  21490. this._isEnabled = value;
  21491. },
  21492. enumerable: true,
  21493. configurable: true
  21494. });
  21495. LensFlareSystem.prototype.getScene = function () {
  21496. return this._scene;
  21497. };
  21498. LensFlareSystem.prototype.getEmitter = function () {
  21499. return this._emitter;
  21500. };
  21501. LensFlareSystem.prototype.getEmitterPosition = function () {
  21502. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  21503. };
  21504. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  21505. var position = this.getEmitterPosition();
  21506. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  21507. this._positionX = position.x;
  21508. this._positionY = position.y;
  21509. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  21510. if (position.z > 0) {
  21511. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  21512. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  21513. return true;
  21514. }
  21515. }
  21516. return false;
  21517. };
  21518. LensFlareSystem.prototype._isVisible = function () {
  21519. if (!this._isEnabled) {
  21520. return false;
  21521. }
  21522. var emitterPosition = this.getEmitterPosition();
  21523. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  21524. var distance = direction.length();
  21525. direction.normalize();
  21526. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  21527. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  21528. return !pickInfo.hit || pickInfo.distance > distance;
  21529. };
  21530. LensFlareSystem.prototype.render = function () {
  21531. if (!this._effect.isReady())
  21532. return false;
  21533. var engine = this._scene.getEngine();
  21534. var viewport = this._scene.activeCamera.viewport;
  21535. var globalViewport = viewport.toGlobal(engine);
  21536. // Position
  21537. if (!this.computeEffectivePosition(globalViewport)) {
  21538. return false;
  21539. }
  21540. // Visibility
  21541. if (!this._isVisible()) {
  21542. return false;
  21543. }
  21544. // Intensity
  21545. var awayX;
  21546. var awayY;
  21547. if (this._positionX < this.borderLimit + globalViewport.x) {
  21548. awayX = this.borderLimit + globalViewport.x - this._positionX;
  21549. }
  21550. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  21551. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  21552. }
  21553. else {
  21554. awayX = 0;
  21555. }
  21556. if (this._positionY < this.borderLimit + globalViewport.y) {
  21557. awayY = this.borderLimit + globalViewport.y - this._positionY;
  21558. }
  21559. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  21560. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  21561. }
  21562. else {
  21563. awayY = 0;
  21564. }
  21565. var away = (awayX > awayY) ? awayX : awayY;
  21566. if (away > this.borderLimit) {
  21567. away = this.borderLimit;
  21568. }
  21569. var intensity = 1.0 - (away / this.borderLimit);
  21570. if (intensity < 0) {
  21571. return false;
  21572. }
  21573. if (intensity > 1.0) {
  21574. intensity = 1.0;
  21575. }
  21576. // Position
  21577. var centerX = globalViewport.x + globalViewport.width / 2;
  21578. var centerY = globalViewport.y + globalViewport.height / 2;
  21579. var distX = centerX - this._positionX;
  21580. var distY = centerY - this._positionY;
  21581. // Effects
  21582. engine.enableEffect(this._effect);
  21583. engine.setState(false);
  21584. engine.setDepthBuffer(false);
  21585. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  21586. // VBOs
  21587. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21588. for (var index = 0; index < this.lensFlares.length; index++) {
  21589. var flare = this.lensFlares[index];
  21590. var x = centerX - (distX * flare.position);
  21591. var y = centerY - (distY * flare.position);
  21592. var cw = flare.size;
  21593. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  21594. var cx = 2 * (x / globalViewport.width) - 1.0;
  21595. var cy = 1.0 - 2 * (y / globalViewport.height);
  21596. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  21597. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  21598. // Texture
  21599. this._effect.setTexture("textureSampler", flare.texture);
  21600. // Color
  21601. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  21602. // Draw order
  21603. engine.draw(true, 0, 6);
  21604. }
  21605. engine.setDepthBuffer(true);
  21606. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21607. return true;
  21608. };
  21609. LensFlareSystem.prototype.dispose = function () {
  21610. if (this._vertexBuffer) {
  21611. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21612. this._vertexBuffer = null;
  21613. }
  21614. if (this._indexBuffer) {
  21615. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21616. this._indexBuffer = null;
  21617. }
  21618. while (this.lensFlares.length) {
  21619. this.lensFlares[0].dispose();
  21620. }
  21621. // Remove from scene
  21622. var index = this._scene.lensFlareSystems.indexOf(this);
  21623. this._scene.lensFlareSystems.splice(index, 1);
  21624. };
  21625. return LensFlareSystem;
  21626. })();
  21627. BABYLON.LensFlareSystem = LensFlareSystem;
  21628. })(BABYLON || (BABYLON = {}));
  21629. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  21630. var BABYLON;
  21631. (function (BABYLON) {
  21632. var CannonJSPlugin = (function () {
  21633. function CannonJSPlugin() {
  21634. this._registeredMeshes = [];
  21635. this._physicsMaterials = [];
  21636. this.updateBodyPosition = function (mesh) {
  21637. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21638. var registeredMesh = this._registeredMeshes[index];
  21639. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21640. var body = registeredMesh.body;
  21641. var center = mesh.getBoundingInfo().boundingBox.center;
  21642. body.position.set(center.x, center.z, center.y);
  21643. body.quaternion.x = mesh.rotationQuaternion.x;
  21644. body.quaternion.z = mesh.rotationQuaternion.y;
  21645. body.quaternion.y = mesh.rotationQuaternion.z;
  21646. body.quaternion.w = -mesh.rotationQuaternion.w;
  21647. return;
  21648. }
  21649. }
  21650. };
  21651. }
  21652. CannonJSPlugin.prototype.initialize = function (iterations) {
  21653. if (iterations === void 0) { iterations = 10; }
  21654. this._world = new CANNON.World();
  21655. this._world.broadphase = new CANNON.NaiveBroadphase();
  21656. this._world.solver.iterations = iterations;
  21657. };
  21658. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21659. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21660. };
  21661. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21662. this._world.step(delta);
  21663. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21664. var registeredMesh = this._registeredMeshes[index];
  21665. if (registeredMesh.isChild) {
  21666. continue;
  21667. }
  21668. // Body position
  21669. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21670. var deltaPos = registeredMesh.delta;
  21671. if (deltaPos) {
  21672. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21673. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21674. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21675. }
  21676. else {
  21677. registeredMesh.mesh.position.x = bodyX;
  21678. registeredMesh.mesh.position.y = bodyZ;
  21679. registeredMesh.mesh.position.z = bodyY;
  21680. }
  21681. if (!registeredMesh.mesh.rotationQuaternion) {
  21682. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21683. }
  21684. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21685. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21686. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21687. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21688. }
  21689. };
  21690. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21691. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21692. };
  21693. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21694. this.unregisterMesh(mesh);
  21695. mesh.computeWorldMatrix(true);
  21696. switch (impostor) {
  21697. case BABYLON.PhysicsEngine.SphereImpostor:
  21698. var bbox = mesh.getBoundingInfo().boundingBox;
  21699. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21700. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21701. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21702. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21703. case BABYLON.PhysicsEngine.BoxImpostor:
  21704. bbox = mesh.getBoundingInfo().boundingBox;
  21705. var min = bbox.minimumWorld;
  21706. var max = bbox.maximumWorld;
  21707. var box = max.subtract(min).scale(0.5);
  21708. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21709. case BABYLON.PhysicsEngine.PlaneImpostor:
  21710. return this._createPlane(mesh, options);
  21711. case BABYLON.PhysicsEngine.MeshImpostor:
  21712. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21713. var rawFaces = mesh.getIndices();
  21714. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21715. }
  21716. return null;
  21717. };
  21718. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21719. var shape = new CANNON.Sphere(radius);
  21720. if (!options) {
  21721. return shape;
  21722. }
  21723. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21724. };
  21725. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21726. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21727. if (!options) {
  21728. return shape;
  21729. }
  21730. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21731. };
  21732. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21733. var shape = new CANNON.Plane();
  21734. if (!options) {
  21735. return shape;
  21736. }
  21737. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21738. };
  21739. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21740. var verts = [], faces = [];
  21741. mesh.computeWorldMatrix(true);
  21742. for (var i = 0; i < rawVerts.length; i += 3) {
  21743. var transformed = BABYLON.Vector3.Zero();
  21744. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21745. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21746. }
  21747. for (var j = 0; j < rawFaces.length; j += 3) {
  21748. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21749. }
  21750. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21751. if (!options) {
  21752. return shape;
  21753. }
  21754. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21755. };
  21756. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21757. var index;
  21758. var mat;
  21759. for (index = 0; index < this._physicsMaterials.length; index++) {
  21760. mat = this._physicsMaterials[index];
  21761. if (mat.friction === friction && mat.restitution === restitution) {
  21762. return mat;
  21763. }
  21764. }
  21765. var currentMat = new CANNON.Material();
  21766. currentMat.friction = friction;
  21767. currentMat.restitution = restitution;
  21768. this._physicsMaterials.push(currentMat);
  21769. for (index = 0; index < this._physicsMaterials.length; index++) {
  21770. mat = this._physicsMaterials[index];
  21771. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21772. contactMaterial.contactEquationStiffness = 1e10;
  21773. contactMaterial.contactEquationRegularizationTime = 10;
  21774. this._world.addContactMaterial(contactMaterial);
  21775. }
  21776. return currentMat;
  21777. };
  21778. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21779. var initialRotation = null;
  21780. if (mesh.rotationQuaternion) {
  21781. initialRotation = mesh.rotationQuaternion.clone();
  21782. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21783. }
  21784. // The delta between the mesh position and the mesh bounding box center
  21785. var bbox = mesh.getBoundingInfo().boundingBox;
  21786. var deltaPosition = mesh.position.subtract(bbox.center);
  21787. var material = this._addMaterial(friction, restitution);
  21788. var body = new CANNON.RigidBody(mass, shape, material);
  21789. if (initialRotation) {
  21790. body.quaternion.x = initialRotation.x;
  21791. body.quaternion.z = initialRotation.y;
  21792. body.quaternion.y = initialRotation.z;
  21793. body.quaternion.w = -initialRotation.w;
  21794. }
  21795. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21796. this._world.add(body);
  21797. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21798. return body;
  21799. };
  21800. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21801. var compoundShape = new CANNON.Compound();
  21802. for (var index = 0; index < parts.length; index++) {
  21803. var mesh = parts[index].mesh;
  21804. var shape = this.registerMesh(mesh, parts[index].impostor);
  21805. if (index == 0) {
  21806. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21807. }
  21808. else {
  21809. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21810. }
  21811. }
  21812. var initialMesh = parts[0].mesh;
  21813. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21814. body.parts = parts;
  21815. return body;
  21816. };
  21817. CannonJSPlugin.prototype._unbindBody = function (body) {
  21818. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21819. var registeredMesh = this._registeredMeshes[index];
  21820. if (registeredMesh.body === body) {
  21821. registeredMesh.body = null;
  21822. registeredMesh.delta = 0;
  21823. }
  21824. }
  21825. };
  21826. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21827. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21828. var registeredMesh = this._registeredMeshes[index];
  21829. if (registeredMesh.mesh === mesh) {
  21830. // Remove body
  21831. if (registeredMesh.body) {
  21832. this._world.remove(registeredMesh.body);
  21833. this._unbindBody(registeredMesh.body);
  21834. }
  21835. this._registeredMeshes.splice(index, 1);
  21836. return;
  21837. }
  21838. }
  21839. };
  21840. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21841. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21842. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21843. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21844. var registeredMesh = this._registeredMeshes[index];
  21845. if (registeredMesh.mesh === mesh) {
  21846. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21847. return;
  21848. }
  21849. }
  21850. };
  21851. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21852. var body1 = null, body2 = null;
  21853. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21854. var registeredMesh = this._registeredMeshes[index];
  21855. if (registeredMesh.mesh === mesh1) {
  21856. body1 = registeredMesh.body;
  21857. }
  21858. else if (registeredMesh.mesh === mesh2) {
  21859. body2 = registeredMesh.body;
  21860. }
  21861. }
  21862. if (!body1 || !body2) {
  21863. return false;
  21864. }
  21865. 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));
  21866. this._world.addConstraint(constraint);
  21867. return true;
  21868. };
  21869. CannonJSPlugin.prototype.dispose = function () {
  21870. while (this._registeredMeshes.length) {
  21871. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21872. }
  21873. };
  21874. CannonJSPlugin.prototype.isSupported = function () {
  21875. return window.CANNON !== undefined;
  21876. };
  21877. return CannonJSPlugin;
  21878. })();
  21879. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21880. })(BABYLON || (BABYLON = {}));
  21881. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21882. var BABYLON;
  21883. (function (BABYLON) {
  21884. var OimoJSPlugin = (function () {
  21885. function OimoJSPlugin() {
  21886. this._registeredMeshes = [];
  21887. /**
  21888. * Update the body position according to the mesh position
  21889. * @param mesh
  21890. */
  21891. this.updateBodyPosition = function (mesh) {
  21892. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21893. var registeredMesh = this._registeredMeshes[index];
  21894. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21895. var body = registeredMesh.body.body;
  21896. mesh.computeWorldMatrix(true);
  21897. var center = mesh.getBoundingInfo().boundingBox.center;
  21898. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  21899. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  21900. body.sleeping = false;
  21901. return;
  21902. }
  21903. // Case where the parent has been updated
  21904. if (registeredMesh.mesh.parent === mesh) {
  21905. mesh.computeWorldMatrix(true);
  21906. registeredMesh.mesh.computeWorldMatrix(true);
  21907. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  21908. var absoluteRotation = mesh.rotation;
  21909. body = registeredMesh.body.body;
  21910. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  21911. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  21912. body.sleeping = false;
  21913. return;
  21914. }
  21915. }
  21916. };
  21917. }
  21918. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  21919. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21920. };
  21921. OimoJSPlugin.prototype.initialize = function (iterations) {
  21922. this._world = new OIMO.World();
  21923. this._world.clear();
  21924. };
  21925. OimoJSPlugin.prototype.setGravity = function (gravity) {
  21926. this._world.gravity = gravity;
  21927. };
  21928. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21929. var body = null;
  21930. this.unregisterMesh(mesh);
  21931. mesh.computeWorldMatrix(true);
  21932. var initialRotation = null;
  21933. if (mesh.rotationQuaternion) {
  21934. initialRotation = mesh.rotationQuaternion.clone();
  21935. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21936. mesh.computeWorldMatrix(true);
  21937. }
  21938. var bbox = mesh.getBoundingInfo().boundingBox;
  21939. // The delta between the mesh position and the mesh bounding box center
  21940. var deltaPosition = mesh.position.subtract(bbox.center);
  21941. // Transform delta position with the rotation
  21942. if (initialRotation) {
  21943. var m = new BABYLON.Matrix();
  21944. initialRotation.toRotationMatrix(m);
  21945. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  21946. }
  21947. switch (impostor) {
  21948. case BABYLON.PhysicsEngine.SphereImpostor:
  21949. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21950. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21951. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21952. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  21953. body = new OIMO.Body({
  21954. type: 'sphere',
  21955. size: [size],
  21956. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  21957. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  21958. move: options.mass != 0,
  21959. config: [options.mass, options.friction, options.restitution],
  21960. world: this._world
  21961. });
  21962. break;
  21963. case BABYLON.PhysicsEngine.PlaneImpostor:
  21964. case BABYLON.PhysicsEngine.CylinderImpostor:
  21965. case BABYLON.PhysicsEngine.BoxImpostor:
  21966. var min = bbox.minimumWorld;
  21967. var max = bbox.maximumWorld;
  21968. var box = max.subtract(min);
  21969. var sizeX = this._checkWithEpsilon(box.x);
  21970. var sizeY = this._checkWithEpsilon(box.y);
  21971. var sizeZ = this._checkWithEpsilon(box.z);
  21972. body = new OIMO.Body({
  21973. type: 'box',
  21974. size: [sizeX, sizeY, sizeZ],
  21975. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  21976. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  21977. move: options.mass != 0,
  21978. config: [options.mass, options.friction, options.restitution],
  21979. world: this._world
  21980. });
  21981. break;
  21982. }
  21983. //If quaternion was set as the rotation of the object
  21984. if (initialRotation) {
  21985. //We have to access the rigid body's properties to set the quaternion.
  21986. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  21987. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  21988. //update the internal rotation matrix
  21989. body.body.syncShapes();
  21990. }
  21991. this._registeredMeshes.push({
  21992. mesh: mesh,
  21993. body: body,
  21994. delta: deltaPosition
  21995. });
  21996. return body;
  21997. };
  21998. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21999. var types = [], sizes = [], positions = [], rotations = [];
  22000. var initialMesh = parts[0].mesh;
  22001. for (var index = 0; index < parts.length; index++) {
  22002. var part = parts[index];
  22003. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  22004. types.push(bodyParameters.type);
  22005. sizes.push.apply(sizes, bodyParameters.size);
  22006. positions.push.apply(positions, bodyParameters.pos);
  22007. rotations.push.apply(rotations, bodyParameters.rot);
  22008. }
  22009. var body = new OIMO.Body({
  22010. type: types,
  22011. size: sizes,
  22012. pos: positions,
  22013. rot: rotations,
  22014. move: options.mass != 0,
  22015. config: [options.mass, options.friction, options.restitution],
  22016. world: this._world
  22017. });
  22018. this._registeredMeshes.push({
  22019. mesh: initialMesh,
  22020. body: body
  22021. });
  22022. return body;
  22023. };
  22024. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  22025. var bodyParameters = null;
  22026. var mesh = part.mesh;
  22027. // We need the bounding box/sphere info to compute the physics body
  22028. mesh.computeWorldMatrix();
  22029. switch (part.impostor) {
  22030. case BABYLON.PhysicsEngine.SphereImpostor:
  22031. var bbox = mesh.getBoundingInfo().boundingBox;
  22032. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22033. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22034. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22035. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22036. bodyParameters = {
  22037. type: 'sphere',
  22038. /* bug with oimo : sphere needs 3 sizes in this case */
  22039. size: [size, -1, -1],
  22040. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  22041. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22042. };
  22043. break;
  22044. case BABYLON.PhysicsEngine.PlaneImpostor:
  22045. case BABYLON.PhysicsEngine.BoxImpostor:
  22046. bbox = mesh.getBoundingInfo().boundingBox;
  22047. var min = bbox.minimumWorld;
  22048. var max = bbox.maximumWorld;
  22049. var box = max.subtract(min);
  22050. var sizeX = this._checkWithEpsilon(box.x);
  22051. var sizeY = this._checkWithEpsilon(box.y);
  22052. var sizeZ = this._checkWithEpsilon(box.z);
  22053. var relativePosition = mesh.position;
  22054. bodyParameters = {
  22055. type: 'box',
  22056. size: [sizeX, sizeY, sizeZ],
  22057. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  22058. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22059. };
  22060. break;
  22061. }
  22062. return bodyParameters;
  22063. };
  22064. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  22065. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22066. var registeredMesh = this._registeredMeshes[index];
  22067. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22068. if (registeredMesh.body) {
  22069. this._world.removeRigidBody(registeredMesh.body.body);
  22070. this._unbindBody(registeredMesh.body);
  22071. }
  22072. this._registeredMeshes.splice(index, 1);
  22073. return;
  22074. }
  22075. }
  22076. };
  22077. OimoJSPlugin.prototype._unbindBody = function (body) {
  22078. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22079. var registeredMesh = this._registeredMeshes[index];
  22080. if (registeredMesh.body === body) {
  22081. registeredMesh.body = null;
  22082. }
  22083. }
  22084. };
  22085. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22086. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22087. var registeredMesh = this._registeredMeshes[index];
  22088. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22089. // Get object mass to have a behaviour similar to cannon.js
  22090. var mass = registeredMesh.body.body.massInfo.mass;
  22091. // The force is scaled with the mass of object
  22092. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  22093. return;
  22094. }
  22095. }
  22096. };
  22097. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22098. var body1 = null, body2 = null;
  22099. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22100. var registeredMesh = this._registeredMeshes[index];
  22101. if (registeredMesh.mesh === mesh1) {
  22102. body1 = registeredMesh.body.body;
  22103. }
  22104. else if (registeredMesh.mesh === mesh2) {
  22105. body2 = registeredMesh.body.body;
  22106. }
  22107. }
  22108. if (!body1 || !body2) {
  22109. return false;
  22110. }
  22111. if (!options) {
  22112. options = {};
  22113. }
  22114. new OIMO.Link({
  22115. type: options.type,
  22116. body1: body1,
  22117. body2: body2,
  22118. min: options.min,
  22119. max: options.max,
  22120. axe1: options.axe1,
  22121. axe2: options.axe2,
  22122. pos1: [pivot1.x, pivot1.y, pivot1.z],
  22123. pos2: [pivot2.x, pivot2.y, pivot2.z],
  22124. collision: options.collision,
  22125. spring: options.spring,
  22126. world: this._world
  22127. });
  22128. return true;
  22129. };
  22130. OimoJSPlugin.prototype.dispose = function () {
  22131. this._world.clear();
  22132. while (this._registeredMeshes.length) {
  22133. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22134. }
  22135. };
  22136. OimoJSPlugin.prototype.isSupported = function () {
  22137. return OIMO !== undefined;
  22138. };
  22139. OimoJSPlugin.prototype._getLastShape = function (body) {
  22140. var lastShape = body.shapes;
  22141. while (lastShape.next) {
  22142. lastShape = lastShape.next;
  22143. }
  22144. return lastShape;
  22145. };
  22146. OimoJSPlugin.prototype.runOneStep = function (time) {
  22147. this._world.step();
  22148. // Update the position of all registered meshes
  22149. var i = this._registeredMeshes.length;
  22150. var m;
  22151. while (i--) {
  22152. var body = this._registeredMeshes[i].body.body;
  22153. var mesh = this._registeredMeshes[i].mesh;
  22154. var delta = this._registeredMeshes[i].delta;
  22155. if (!body.sleeping) {
  22156. if (body.shapes.next) {
  22157. var parentShape = this._getLastShape(body);
  22158. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  22159. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  22160. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  22161. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  22162. if (!mesh.rotationQuaternion) {
  22163. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22164. }
  22165. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  22166. mesh.computeWorldMatrix();
  22167. }
  22168. else {
  22169. m = body.getMatrix();
  22170. mtx = BABYLON.Matrix.FromArray(m);
  22171. // Body position
  22172. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  22173. if (!delta) {
  22174. mesh.position.x = bodyX;
  22175. mesh.position.y = bodyY;
  22176. mesh.position.z = bodyZ;
  22177. }
  22178. else {
  22179. mesh.position.x = bodyX + delta.x;
  22180. mesh.position.y = bodyY + delta.y;
  22181. mesh.position.z = bodyZ + delta.z;
  22182. }
  22183. if (!mesh.rotationQuaternion) {
  22184. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22185. }
  22186. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  22187. mesh.computeWorldMatrix();
  22188. }
  22189. }
  22190. }
  22191. };
  22192. return OimoJSPlugin;
  22193. })();
  22194. BABYLON.OimoJSPlugin = OimoJSPlugin;
  22195. })(BABYLON || (BABYLON = {}));
  22196. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  22197. var BABYLON;
  22198. (function (BABYLON) {
  22199. var PhysicsEngine = (function () {
  22200. function PhysicsEngine(plugin) {
  22201. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22202. }
  22203. PhysicsEngine.prototype._initialize = function (gravity) {
  22204. this._currentPlugin.initialize();
  22205. this._setGravity(gravity);
  22206. };
  22207. PhysicsEngine.prototype._runOneStep = function (delta) {
  22208. if (delta > 0.1) {
  22209. delta = 0.1;
  22210. }
  22211. else if (delta <= 0) {
  22212. delta = 1.0 / 60.0;
  22213. }
  22214. this._currentPlugin.runOneStep(delta);
  22215. };
  22216. PhysicsEngine.prototype._setGravity = function (gravity) {
  22217. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  22218. this._currentPlugin.setGravity(this.gravity);
  22219. };
  22220. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22221. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22222. };
  22223. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22224. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22225. };
  22226. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22227. this._currentPlugin.unregisterMesh(mesh);
  22228. };
  22229. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22230. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22231. };
  22232. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22233. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22234. };
  22235. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22236. this._currentPlugin.updateBodyPosition(mesh);
  22237. };
  22238. PhysicsEngine.prototype.dispose = function () {
  22239. this._currentPlugin.dispose();
  22240. };
  22241. PhysicsEngine.prototype.isSupported = function () {
  22242. return this._currentPlugin.isSupported();
  22243. };
  22244. // Statics
  22245. PhysicsEngine.NoImpostor = 0;
  22246. PhysicsEngine.SphereImpostor = 1;
  22247. PhysicsEngine.BoxImpostor = 2;
  22248. PhysicsEngine.PlaneImpostor = 3;
  22249. PhysicsEngine.MeshImpostor = 4;
  22250. PhysicsEngine.CapsuleImpostor = 5;
  22251. PhysicsEngine.ConeImpostor = 6;
  22252. PhysicsEngine.CylinderImpostor = 7;
  22253. PhysicsEngine.ConvexHullImpostor = 8;
  22254. PhysicsEngine.Epsilon = 0.001;
  22255. return PhysicsEngine;
  22256. })();
  22257. BABYLON.PhysicsEngine = PhysicsEngine;
  22258. })(BABYLON || (BABYLON = {}));
  22259. //# sourceMappingURL=babylon.physicsEngine.js.map
  22260. var BABYLON;
  22261. (function (BABYLON) {
  22262. var serializeLight = function (light) {
  22263. var serializationObject = {};
  22264. serializationObject.name = light.name;
  22265. serializationObject.id = light.id;
  22266. serializationObject.tags = BABYLON.Tags.GetTags(light);
  22267. if (light instanceof BABYLON.PointLight) {
  22268. serializationObject.type = 0;
  22269. serializationObject.position = light.position.asArray();
  22270. }
  22271. else if (light instanceof BABYLON.DirectionalLight) {
  22272. serializationObject.type = 1;
  22273. var directionalLight = light;
  22274. serializationObject.position = directionalLight.position.asArray();
  22275. serializationObject.direction = directionalLight.direction.asArray();
  22276. }
  22277. else if (light instanceof BABYLON.SpotLight) {
  22278. serializationObject.type = 2;
  22279. var spotLight = light;
  22280. serializationObject.position = spotLight.position.asArray();
  22281. serializationObject.direction = spotLight.position.asArray();
  22282. serializationObject.angle = spotLight.angle;
  22283. serializationObject.exponent = spotLight.exponent;
  22284. }
  22285. else if (light instanceof BABYLON.HemisphericLight) {
  22286. serializationObject.type = 3;
  22287. var hemisphericLight = light;
  22288. serializationObject.direction = hemisphericLight.direction.asArray();
  22289. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  22290. }
  22291. if (light.intensity) {
  22292. serializationObject.intensity = light.intensity;
  22293. }
  22294. serializationObject.range = light.range;
  22295. serializationObject.diffuse = light.diffuse.asArray();
  22296. serializationObject.specular = light.specular.asArray();
  22297. return serializationObject;
  22298. };
  22299. var serializeFresnelParameter = function (fresnelParameter) {
  22300. var serializationObject = {};
  22301. serializationObject.isEnabled = fresnelParameter.isEnabled;
  22302. serializationObject.leftColor = fresnelParameter.leftColor;
  22303. serializationObject.rightColor = fresnelParameter.rightColor;
  22304. serializationObject.bias = fresnelParameter.bias;
  22305. serializationObject.power = fresnelParameter.power;
  22306. return serializationObject;
  22307. };
  22308. var appendAnimations = function (source, destination) {
  22309. if (source.animations) {
  22310. destination.animations = [];
  22311. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  22312. var animation = source.animations[animationIndex];
  22313. destination.animations.push(serializeAnimation(animation));
  22314. }
  22315. }
  22316. };
  22317. var serializeCamera = function (camera) {
  22318. var serializationObject = {};
  22319. serializationObject.name = camera.name;
  22320. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  22321. serializationObject.id = camera.id;
  22322. serializationObject.position = camera.position.asArray();
  22323. // Parent
  22324. if (camera.parent) {
  22325. serializationObject.parentId = camera.parent.id;
  22326. }
  22327. serializationObject.fov = camera.fov;
  22328. serializationObject.minZ = camera.minZ;
  22329. serializationObject.maxZ = camera.maxZ;
  22330. serializationObject.inertia = camera.inertia;
  22331. //setting the type
  22332. if (camera instanceof BABYLON.FreeCamera) {
  22333. serializationObject.type = "FreeCamera";
  22334. }
  22335. else if (camera instanceof BABYLON.ArcRotateCamera) {
  22336. serializationObject.type = "ArcRotateCamera";
  22337. }
  22338. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  22339. serializationObject.type = "AnaglyphArcRotateCamera";
  22340. }
  22341. else if (camera instanceof BABYLON.GamepadCamera) {
  22342. serializationObject.type = "GamepadCamera";
  22343. }
  22344. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  22345. serializationObject.type = "AnaglyphFreeCamera";
  22346. }
  22347. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  22348. serializationObject.type = "DeviceOrientationCamera";
  22349. }
  22350. else if (camera instanceof BABYLON.FollowCamera) {
  22351. serializationObject.type = "FollowCamera";
  22352. }
  22353. else if (camera instanceof BABYLON.TouchCamera) {
  22354. serializationObject.type = "TouchCamera";
  22355. }
  22356. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  22357. serializationObject.type = "VirtualJoysticksCamera";
  22358. }
  22359. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  22360. serializationObject.type = "WebVRCamera";
  22361. }
  22362. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  22363. serializationObject.type = "VRDeviceOrientationCamera";
  22364. }
  22365. //special properties of specific cameras
  22366. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  22367. var arcCamera = camera;
  22368. serializationObject.alpha = arcCamera.alpha;
  22369. serializationObject.beta = arcCamera.beta;
  22370. serializationObject.radius = arcCamera.radius;
  22371. if (arcCamera.target && arcCamera.target.id) {
  22372. serializationObject.lockedTargetId = arcCamera.target.id;
  22373. }
  22374. }
  22375. else if (camera instanceof BABYLON.FollowCamera) {
  22376. var followCam = camera;
  22377. serializationObject.radius = followCam.radius;
  22378. serializationObject.heightOffset = followCam.heightOffset;
  22379. serializationObject.rotationOffset = followCam.rotationOffset;
  22380. }
  22381. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  22382. //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.
  22383. if (camera['_eyeSpace'] !== undefined) {
  22384. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  22385. }
  22386. }
  22387. //general properties that not all cameras have. The [] is due to typescript's type safety
  22388. if (camera['speed'] !== undefined) {
  22389. serializationObject.speed = camera['speed'];
  22390. }
  22391. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  22392. serializationObject.target = camera['target'].asArray();
  22393. }
  22394. // Target
  22395. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  22396. serializationObject.rotation = camera['rotation'].asArray();
  22397. }
  22398. // Locked target
  22399. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  22400. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  22401. }
  22402. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  22403. serializationObject.applyGravity = camera['applyGravity'] || false;
  22404. if (camera['ellipsoid']) {
  22405. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  22406. }
  22407. // Animations
  22408. appendAnimations(camera, serializationObject);
  22409. // Layer mask
  22410. serializationObject.layerMask = camera.layerMask;
  22411. return serializationObject;
  22412. };
  22413. var serializeAnimation = function (animation) {
  22414. var serializationObject = {};
  22415. serializationObject.name = animation.name;
  22416. serializationObject.property = animation.targetProperty;
  22417. serializationObject.framePerSecond = animation.framePerSecond;
  22418. serializationObject.dataType = animation.dataType;
  22419. serializationObject.loopBehavior = animation.loopMode;
  22420. var dataType = animation.dataType;
  22421. serializationObject.keys = [];
  22422. var keys = animation.getKeys();
  22423. for (var index = 0; index < keys.length; index++) {
  22424. var animationKey = keys[index];
  22425. var key = {};
  22426. key.frame = animationKey.frame;
  22427. switch (dataType) {
  22428. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  22429. key.values = [animationKey.value];
  22430. break;
  22431. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  22432. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  22433. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  22434. key.values = animationKey.value.asArray();
  22435. break;
  22436. }
  22437. serializationObject.keys.push(key);
  22438. }
  22439. return serializationObject;
  22440. };
  22441. var serializeMultiMaterial = function (material) {
  22442. var serializationObject = {};
  22443. serializationObject.name = material.name;
  22444. serializationObject.id = material.id;
  22445. serializationObject.tags = BABYLON.Tags.GetTags(material);
  22446. serializationObject.materials = [];
  22447. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  22448. var subMat = material.subMaterials[matIndex];
  22449. if (subMat) {
  22450. serializationObject.materials.push(subMat.id);
  22451. }
  22452. else {
  22453. serializationObject.materials.push(null);
  22454. }
  22455. }
  22456. return serializationObject;
  22457. };
  22458. var serializeMaterial = function (material) {
  22459. var serializationObject = {};
  22460. serializationObject.name = material.name;
  22461. serializationObject.ambient = material.ambientColor.asArray();
  22462. serializationObject.diffuse = material.diffuseColor.asArray();
  22463. serializationObject.specular = material.specularColor.asArray();
  22464. serializationObject.specularPower = material.specularPower;
  22465. serializationObject.emissive = material.emissiveColor.asArray();
  22466. serializationObject.alpha = material.alpha;
  22467. serializationObject.id = material.id;
  22468. serializationObject.tags = BABYLON.Tags.GetTags(material);
  22469. serializationObject.backFaceCulling = material.backFaceCulling;
  22470. if (material.diffuseTexture) {
  22471. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  22472. }
  22473. if (material.diffuseFresnelParameters) {
  22474. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  22475. }
  22476. if (material.ambientTexture) {
  22477. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  22478. }
  22479. if (material.opacityTexture) {
  22480. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  22481. }
  22482. if (material.opacityFresnelParameters) {
  22483. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  22484. }
  22485. if (material.reflectionTexture) {
  22486. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  22487. }
  22488. if (material.reflectionFresnelParameters) {
  22489. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  22490. }
  22491. if (material.emissiveTexture) {
  22492. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  22493. }
  22494. if (material.emissiveFresnelParameters) {
  22495. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  22496. }
  22497. if (material.specularTexture) {
  22498. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  22499. }
  22500. if (material.bumpTexture) {
  22501. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  22502. }
  22503. return serializationObject;
  22504. };
  22505. var serializeTexture = function (texture) {
  22506. var serializationObject = {};
  22507. if (!texture.name) {
  22508. return null;
  22509. }
  22510. if (texture instanceof BABYLON.CubeTexture) {
  22511. serializationObject.name = texture.name;
  22512. serializationObject.hasAlpha = texture.hasAlpha;
  22513. serializationObject.level = texture.level;
  22514. serializationObject.coordinatesMode = texture.coordinatesMode;
  22515. return serializationObject;
  22516. }
  22517. if (texture instanceof BABYLON.MirrorTexture) {
  22518. var mirrorTexture = texture;
  22519. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  22520. serializationObject.renderList = [];
  22521. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  22522. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  22523. }
  22524. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  22525. }
  22526. else if (texture instanceof BABYLON.RenderTargetTexture) {
  22527. var renderTargetTexture = texture;
  22528. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  22529. serializationObject.renderList = [];
  22530. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  22531. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  22532. }
  22533. }
  22534. var regularTexture = texture;
  22535. serializationObject.name = texture.name;
  22536. serializationObject.hasAlpha = texture.hasAlpha;
  22537. serializationObject.level = texture.level;
  22538. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  22539. serializationObject.coordinatesMode = texture.coordinatesMode;
  22540. serializationObject.uOffset = regularTexture.uOffset;
  22541. serializationObject.vOffset = regularTexture.vOffset;
  22542. serializationObject.uScale = regularTexture.uScale;
  22543. serializationObject.vScale = regularTexture.vScale;
  22544. serializationObject.uAng = regularTexture.uAng;
  22545. serializationObject.vAng = regularTexture.vAng;
  22546. serializationObject.wAng = regularTexture.wAng;
  22547. serializationObject.wrapU = texture.wrapU;
  22548. serializationObject.wrapV = texture.wrapV;
  22549. // Animations
  22550. appendAnimations(texture, serializationObject);
  22551. return serializationObject;
  22552. };
  22553. var serializeSkeleton = function (skeleton) {
  22554. var serializationObject = {};
  22555. serializationObject.name = skeleton.name;
  22556. serializationObject.id = skeleton.id;
  22557. serializationObject.bones = [];
  22558. for (var index = 0; index < skeleton.bones.length; index++) {
  22559. var bone = skeleton.bones[index];
  22560. var serializedBone = {
  22561. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  22562. name: bone.name,
  22563. matrix: bone.getLocalMatrix().toArray()
  22564. };
  22565. serializationObject.bones.push(serializedBone);
  22566. if (bone.animations && bone.animations.length > 0) {
  22567. serializedBone.animation = serializeAnimation(bone.animations[0]);
  22568. }
  22569. }
  22570. return serializationObject;
  22571. };
  22572. var serializeParticleSystem = function (particleSystem) {
  22573. var serializationObject = {};
  22574. serializationObject.emitterId = particleSystem.emitter.id;
  22575. serializationObject.capacity = particleSystem.getCapacity();
  22576. if (particleSystem.particleTexture) {
  22577. serializationObject.textureName = particleSystem.particleTexture.name;
  22578. }
  22579. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  22580. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  22581. serializationObject.minSize = particleSystem.minSize;
  22582. serializationObject.maxSize = particleSystem.maxSize;
  22583. serializationObject.minLifeTime = particleSystem.minLifeTime;
  22584. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  22585. serializationObject.emitRate = particleSystem.emitRate;
  22586. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  22587. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  22588. serializationObject.gravity = particleSystem.gravity.asArray();
  22589. serializationObject.direction1 = particleSystem.direction1.asArray();
  22590. serializationObject.direction2 = particleSystem.direction2.asArray();
  22591. serializationObject.color1 = particleSystem.color1.asArray();
  22592. serializationObject.color2 = particleSystem.color2.asArray();
  22593. serializationObject.colorDead = particleSystem.colorDead.asArray();
  22594. serializationObject.updateSpeed = particleSystem.updateSpeed;
  22595. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  22596. serializationObject.textureMask = particleSystem.textureMask.asArray();
  22597. serializationObject.blendMode = particleSystem.blendMode;
  22598. return serializationObject;
  22599. };
  22600. var serializeLensFlareSystem = function (lensFlareSystem) {
  22601. var serializationObject = {};
  22602. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  22603. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  22604. serializationObject.flares = [];
  22605. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  22606. var flare = lensFlareSystem.lensFlares[index];
  22607. serializationObject.flares.push({
  22608. size: flare.size,
  22609. position: flare.position,
  22610. color: flare.color.asArray(),
  22611. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  22612. });
  22613. }
  22614. return serializationObject;
  22615. };
  22616. var serializeShadowGenerator = function (light) {
  22617. var serializationObject = {};
  22618. var shadowGenerator = light.getShadowGenerator();
  22619. serializationObject.lightId = light.id;
  22620. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  22621. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  22622. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  22623. serializationObject.renderList = [];
  22624. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  22625. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  22626. serializationObject.renderList.push(mesh.id);
  22627. }
  22628. return serializationObject;
  22629. };
  22630. var serializedGeometries = [];
  22631. var serializeGeometry = function (geometry, serializationGeometries) {
  22632. if (serializedGeometries[geometry.id]) {
  22633. return;
  22634. }
  22635. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  22636. serializationGeometries.boxes.push(serializeBox(geometry));
  22637. }
  22638. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  22639. serializationGeometries.spheres.push(serializeSphere(geometry));
  22640. }
  22641. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  22642. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  22643. }
  22644. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  22645. serializationGeometries.toruses.push(serializeTorus(geometry));
  22646. }
  22647. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  22648. serializationGeometries.grounds.push(serializeGround(geometry));
  22649. }
  22650. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  22651. serializationGeometries.planes.push(serializePlane(geometry));
  22652. }
  22653. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  22654. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  22655. }
  22656. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  22657. throw new Error("Unknow primitive type");
  22658. }
  22659. else {
  22660. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  22661. }
  22662. serializedGeometries[geometry.id] = true;
  22663. };
  22664. var serializeGeometryBase = function (geometry) {
  22665. var serializationObject = {};
  22666. serializationObject.id = geometry.id;
  22667. if (BABYLON.Tags.HasTags(geometry)) {
  22668. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  22669. }
  22670. return serializationObject;
  22671. };
  22672. var serializeVertexData = function (vertexData) {
  22673. var serializationObject = serializeGeometryBase(vertexData);
  22674. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22675. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22676. }
  22677. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22678. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22679. }
  22680. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22681. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22682. }
  22683. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22684. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22685. }
  22686. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22687. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22688. }
  22689. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22690. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22691. serializationObject.matricesIndices._isExpanded = true;
  22692. }
  22693. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22694. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22695. }
  22696. serializationObject.indices = vertexData.getIndices();
  22697. return serializationObject;
  22698. };
  22699. var serializePrimitive = function (primitive) {
  22700. var serializationObject = serializeGeometryBase(primitive);
  22701. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  22702. return serializationObject;
  22703. };
  22704. var serializeBox = function (box) {
  22705. var serializationObject = serializePrimitive(box);
  22706. serializationObject.size = box.size;
  22707. return serializationObject;
  22708. };
  22709. var serializeSphere = function (sphere) {
  22710. var serializationObject = serializePrimitive(sphere);
  22711. serializationObject.segments = sphere.segments;
  22712. serializationObject.diameter = sphere.diameter;
  22713. return serializationObject;
  22714. };
  22715. var serializeCylinder = function (cylinder) {
  22716. var serializationObject = serializePrimitive(cylinder);
  22717. serializationObject.height = cylinder.height;
  22718. serializationObject.diameterTop = cylinder.diameterTop;
  22719. serializationObject.diameterBottom = cylinder.diameterBottom;
  22720. serializationObject.tessellation = cylinder.tessellation;
  22721. return serializationObject;
  22722. };
  22723. var serializeTorus = function (torus) {
  22724. var serializationObject = serializePrimitive(torus);
  22725. serializationObject.diameter = torus.diameter;
  22726. serializationObject.thickness = torus.thickness;
  22727. serializationObject.tessellation = torus.tessellation;
  22728. return serializationObject;
  22729. };
  22730. var serializeGround = function (ground) {
  22731. var serializationObject = serializePrimitive(ground);
  22732. serializationObject.width = ground.width;
  22733. serializationObject.height = ground.height;
  22734. serializationObject.subdivisions = ground.subdivisions;
  22735. return serializationObject;
  22736. };
  22737. var serializePlane = function (plane) {
  22738. var serializationObject = serializePrimitive(plane);
  22739. serializationObject.size = plane.size;
  22740. return serializationObject;
  22741. };
  22742. var serializeTorusKnot = function (torusKnot) {
  22743. var serializationObject = serializePrimitive(torusKnot);
  22744. serializationObject.radius = torusKnot.radius;
  22745. serializationObject.tube = torusKnot.tube;
  22746. serializationObject.radialSegments = torusKnot.radialSegments;
  22747. serializationObject.tubularSegments = torusKnot.tubularSegments;
  22748. serializationObject.p = torusKnot.p;
  22749. serializationObject.q = torusKnot.q;
  22750. return serializationObject;
  22751. };
  22752. var serializeMesh = function (mesh, serializationScene) {
  22753. var serializationObject = {};
  22754. serializationObject.name = mesh.name;
  22755. serializationObject.id = mesh.id;
  22756. if (BABYLON.Tags.HasTags(mesh)) {
  22757. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  22758. }
  22759. serializationObject.position = mesh.position.asArray();
  22760. if (mesh.rotationQuaternion) {
  22761. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  22762. }
  22763. else if (mesh.rotation) {
  22764. serializationObject.rotation = mesh.rotation.asArray();
  22765. }
  22766. serializationObject.scaling = mesh.scaling.asArray();
  22767. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  22768. serializationObject.isEnabled = mesh.isEnabled();
  22769. serializationObject.isVisible = mesh.isVisible;
  22770. serializationObject.infiniteDistance = mesh.infiniteDistance;
  22771. serializationObject.pickable = mesh.isPickable;
  22772. serializationObject.receiveShadows = mesh.receiveShadows;
  22773. serializationObject.billboardMode = mesh.billboardMode;
  22774. serializationObject.visibility = mesh.visibility;
  22775. serializationObject.checkCollisions = mesh.checkCollisions;
  22776. // Parent
  22777. if (mesh.parent) {
  22778. serializationObject.parentId = mesh.parent.id;
  22779. }
  22780. // Geometry
  22781. var geometry = mesh._geometry;
  22782. if (geometry) {
  22783. var geometryId = geometry.id;
  22784. serializationObject.geometryId = geometryId;
  22785. if (!mesh.getScene().getGeometryByID(geometryId)) {
  22786. // 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
  22787. serializeGeometry(geometry, serializationScene.geometries);
  22788. }
  22789. // SubMeshes
  22790. serializationObject.subMeshes = [];
  22791. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22792. var subMesh = mesh.subMeshes[subIndex];
  22793. serializationObject.subMeshes.push({
  22794. materialIndex: subMesh.materialIndex,
  22795. verticesStart: subMesh.verticesStart,
  22796. verticesCount: subMesh.verticesCount,
  22797. indexStart: subMesh.indexStart,
  22798. indexCount: subMesh.indexCount
  22799. });
  22800. }
  22801. }
  22802. // Material
  22803. if (mesh.material) {
  22804. serializationObject.materialId = mesh.material.id;
  22805. }
  22806. else {
  22807. mesh.material = null;
  22808. }
  22809. // Skeleton
  22810. if (mesh.skeleton) {
  22811. serializationObject.skeletonId = mesh.skeleton.id;
  22812. }
  22813. // Physics
  22814. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  22815. serializationObject.physicsMass = mesh.getPhysicsMass();
  22816. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  22817. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  22818. switch (mesh.getPhysicsImpostor()) {
  22819. case BABYLON.PhysicsEngine.BoxImpostor:
  22820. serializationObject.physicsImpostor = 1;
  22821. break;
  22822. case BABYLON.PhysicsEngine.SphereImpostor:
  22823. serializationObject.physicsImpostor = 2;
  22824. break;
  22825. }
  22826. }
  22827. // Instances
  22828. serializationObject.instances = [];
  22829. for (var index = 0; index < mesh.instances.length; index++) {
  22830. var instance = mesh.instances[index];
  22831. var serializationInstance = {
  22832. name: instance.name,
  22833. position: instance.position,
  22834. rotation: instance.rotation,
  22835. rotationQuaternion: instance.rotationQuaternion,
  22836. scaling: instance.scaling
  22837. };
  22838. serializationObject.instances.push(serializationInstance);
  22839. // Animations
  22840. appendAnimations(instance, serializationInstance);
  22841. }
  22842. // Animations
  22843. appendAnimations(mesh, serializationObject);
  22844. // Layer mask
  22845. serializationObject.layerMask = mesh.layerMask;
  22846. return serializationObject;
  22847. };
  22848. var SceneSerializer = (function () {
  22849. function SceneSerializer() {
  22850. }
  22851. SceneSerializer.Serialize = function (scene) {
  22852. var serializationObject = {};
  22853. // Scene
  22854. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  22855. serializationObject.autoClear = scene.autoClear;
  22856. serializationObject.clearColor = scene.clearColor.asArray();
  22857. serializationObject.ambientColor = scene.ambientColor.asArray();
  22858. serializationObject.gravity = scene.gravity.asArray();
  22859. // Fog
  22860. if (scene.fogMode && scene.fogMode !== 0) {
  22861. serializationObject.fogMode = scene.fogMode;
  22862. serializationObject.fogColor = scene.fogColor.asArray();
  22863. serializationObject.fogStart = scene.fogStart;
  22864. serializationObject.fogEnd = scene.fogEnd;
  22865. serializationObject.fogDensity = scene.fogDensity;
  22866. }
  22867. // Lights
  22868. serializationObject.lights = [];
  22869. for (var index = 0; index < scene.lights.length; index++) {
  22870. var light = scene.lights[index];
  22871. serializationObject.lights.push(serializeLight(light));
  22872. }
  22873. // Cameras
  22874. serializationObject.cameras = [];
  22875. for (index = 0; index < scene.cameras.length; index++) {
  22876. var camera = scene.cameras[index];
  22877. serializationObject.cameras.push(serializeCamera(camera));
  22878. }
  22879. if (scene.activeCamera) {
  22880. serializationObject.activeCameraID = scene.activeCamera.id;
  22881. }
  22882. // Materials
  22883. serializationObject.materials = [];
  22884. serializationObject.multiMaterials = [];
  22885. for (index = 0; index < scene.materials.length; index++) {
  22886. var material = scene.materials[index];
  22887. if (material instanceof BABYLON.StandardMaterial) {
  22888. serializationObject.materials.push(serializeMaterial(material));
  22889. }
  22890. else if (material instanceof BABYLON.MultiMaterial) {
  22891. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  22892. }
  22893. }
  22894. // Skeletons
  22895. serializationObject.skeletons = [];
  22896. for (index = 0; index < scene.skeletons.length; index++) {
  22897. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  22898. }
  22899. // Geometries
  22900. serializationObject.geometries = {};
  22901. serializationObject.geometries.boxes = [];
  22902. serializationObject.geometries.spheres = [];
  22903. serializationObject.geometries.cylinders = [];
  22904. serializationObject.geometries.toruses = [];
  22905. serializationObject.geometries.grounds = [];
  22906. serializationObject.geometries.planes = [];
  22907. serializationObject.geometries.torusKnots = [];
  22908. serializationObject.geometries.vertexData = [];
  22909. serializedGeometries = [];
  22910. var geometries = scene.getGeometries();
  22911. for (index = 0; index < geometries.length; index++) {
  22912. var geometry = geometries[index];
  22913. if (geometry.isReady()) {
  22914. serializeGeometry(geometry, serializationObject.geometries);
  22915. }
  22916. }
  22917. // Meshes
  22918. serializationObject.meshes = [];
  22919. for (index = 0; index < scene.meshes.length; index++) {
  22920. var abstractMesh = scene.meshes[index];
  22921. if (abstractMesh instanceof BABYLON.Mesh) {
  22922. var mesh = abstractMesh;
  22923. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  22924. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  22925. }
  22926. }
  22927. }
  22928. // Particles Systems
  22929. serializationObject.particleSystems = [];
  22930. for (index = 0; index < scene.particleSystems.length; index++) {
  22931. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  22932. }
  22933. // Lens flares
  22934. serializationObject.lensFlareSystems = [];
  22935. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  22936. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  22937. }
  22938. // Shadows
  22939. serializationObject.shadowGenerators = [];
  22940. for (index = 0; index < scene.lights.length; index++) {
  22941. light = scene.lights[index];
  22942. if (light.getShadowGenerator()) {
  22943. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  22944. }
  22945. }
  22946. return serializationObject;
  22947. };
  22948. return SceneSerializer;
  22949. })();
  22950. BABYLON.SceneSerializer = SceneSerializer;
  22951. })(BABYLON || (BABYLON = {}));
  22952. //# sourceMappingURL=babylon.sceneSerializer.js.map
  22953. var BABYLON;
  22954. (function (BABYLON) {
  22955. // Unique ID when we import meshes from Babylon to CSG
  22956. var currentCSGMeshId = 0;
  22957. // # class Vertex
  22958. // Represents a vertex of a polygon. Use your own vertex class instead of this
  22959. // one to provide additional features like texture coordinates and vertex
  22960. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  22961. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  22962. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  22963. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  22964. // is not used anywhere else.
  22965. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  22966. var Vertex = (function () {
  22967. function Vertex(pos, normal, uv) {
  22968. this.pos = pos;
  22969. this.normal = normal;
  22970. this.uv = uv;
  22971. }
  22972. Vertex.prototype.clone = function () {
  22973. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  22974. };
  22975. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  22976. // orientation of a polygon is flipped.
  22977. Vertex.prototype.flip = function () {
  22978. this.normal = this.normal.scale(-1);
  22979. };
  22980. // Create a new vertex between this vertex and `other` by linearly
  22981. // interpolating all properties using a parameter of `t`. Subclasses should
  22982. // override this to interpolate additional properties.
  22983. Vertex.prototype.interpolate = function (other, t) {
  22984. 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));
  22985. };
  22986. return Vertex;
  22987. })();
  22988. // # class Plane
  22989. // Represents a plane in 3D space.
  22990. var Plane = (function () {
  22991. function Plane(normal, w) {
  22992. this.normal = normal;
  22993. this.w = w;
  22994. }
  22995. Plane.FromPoints = function (a, b, c) {
  22996. var v0 = c.subtract(a);
  22997. var v1 = b.subtract(a);
  22998. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  22999. return null;
  23000. }
  23001. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  23002. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  23003. };
  23004. Plane.prototype.clone = function () {
  23005. return new Plane(this.normal.clone(), this.w);
  23006. };
  23007. Plane.prototype.flip = function () {
  23008. this.normal.scaleInPlace(-1);
  23009. this.w = -this.w;
  23010. };
  23011. // Split `polygon` by this plane if needed, then put the polygon or polygon
  23012. // fragments in the appropriate lists. Coplanar polygons go into either
  23013. // `coplanarFront` or `coplanarBack` depending on their orientation with
  23014. // respect to this plane. Polygons in front or in back of this plane go into
  23015. // either `front` or `back`.
  23016. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  23017. var COPLANAR = 0;
  23018. var FRONT = 1;
  23019. var BACK = 2;
  23020. var SPANNING = 3;
  23021. // Classify each point as well as the entire polygon into one of the above
  23022. // four classes.
  23023. var polygonType = 0;
  23024. var types = [];
  23025. for (var i = 0; i < polygon.vertices.length; i++) {
  23026. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  23027. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  23028. polygonType |= type;
  23029. types.push(type);
  23030. }
  23031. switch (polygonType) {
  23032. case COPLANAR:
  23033. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  23034. break;
  23035. case FRONT:
  23036. front.push(polygon);
  23037. break;
  23038. case BACK:
  23039. back.push(polygon);
  23040. break;
  23041. case SPANNING:
  23042. var f = [], b = [];
  23043. for (i = 0; i < polygon.vertices.length; i++) {
  23044. var j = (i + 1) % polygon.vertices.length;
  23045. var ti = types[i], tj = types[j];
  23046. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  23047. if (ti != BACK)
  23048. f.push(vi);
  23049. if (ti != FRONT)
  23050. b.push(ti != BACK ? vi.clone() : vi);
  23051. if ((ti | tj) == SPANNING) {
  23052. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  23053. var v = vi.interpolate(vj, t);
  23054. f.push(v);
  23055. b.push(v.clone());
  23056. }
  23057. }
  23058. if (f.length >= 3) {
  23059. var poly = new Polygon(f, polygon.shared);
  23060. if (poly.plane)
  23061. front.push(poly);
  23062. }
  23063. if (b.length >= 3) {
  23064. poly = new Polygon(b, polygon.shared);
  23065. if (poly.plane)
  23066. back.push(poly);
  23067. }
  23068. break;
  23069. }
  23070. };
  23071. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  23072. // point is on the plane.
  23073. Plane.EPSILON = 1e-5;
  23074. return Plane;
  23075. })();
  23076. // # class Polygon
  23077. // Represents a convex polygon. The vertices used to initialize a polygon must
  23078. // be coplanar and form a convex loop.
  23079. //
  23080. // Each convex polygon has a `shared` property, which is shared between all
  23081. // polygons that are clones of each other or were split from the same polygon.
  23082. // This can be used to define per-polygon properties (such as surface color).
  23083. var Polygon = (function () {
  23084. function Polygon(vertices, shared) {
  23085. this.vertices = vertices;
  23086. this.shared = shared;
  23087. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  23088. }
  23089. Polygon.prototype.clone = function () {
  23090. var vertices = this.vertices.map(function (v) { return v.clone(); });
  23091. return new Polygon(vertices, this.shared);
  23092. };
  23093. Polygon.prototype.flip = function () {
  23094. this.vertices.reverse().map(function (v) {
  23095. v.flip();
  23096. });
  23097. this.plane.flip();
  23098. };
  23099. return Polygon;
  23100. })();
  23101. // # class Node
  23102. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  23103. // by picking a polygon to split along. That polygon (and all other coplanar
  23104. // polygons) are added directly to that node and the other polygons are added to
  23105. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  23106. // no distinction between internal and leaf nodes.
  23107. var Node = (function () {
  23108. function Node(polygons) {
  23109. this.plane = null;
  23110. this.front = null;
  23111. this.back = null;
  23112. this.polygons = [];
  23113. if (polygons) {
  23114. this.build(polygons);
  23115. }
  23116. }
  23117. Node.prototype.clone = function () {
  23118. var node = new Node();
  23119. node.plane = this.plane && this.plane.clone();
  23120. node.front = this.front && this.front.clone();
  23121. node.back = this.back && this.back.clone();
  23122. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  23123. return node;
  23124. };
  23125. // Convert solid space to empty space and empty space to solid space.
  23126. Node.prototype.invert = function () {
  23127. for (var i = 0; i < this.polygons.length; i++) {
  23128. this.polygons[i].flip();
  23129. }
  23130. if (this.plane) {
  23131. this.plane.flip();
  23132. }
  23133. if (this.front) {
  23134. this.front.invert();
  23135. }
  23136. if (this.back) {
  23137. this.back.invert();
  23138. }
  23139. var temp = this.front;
  23140. this.front = this.back;
  23141. this.back = temp;
  23142. };
  23143. // Recursively remove all polygons in `polygons` that are inside this BSP
  23144. // tree.
  23145. Node.prototype.clipPolygons = function (polygons) {
  23146. if (!this.plane)
  23147. return polygons.slice();
  23148. var front = [], back = [];
  23149. for (var i = 0; i < polygons.length; i++) {
  23150. this.plane.splitPolygon(polygons[i], front, back, front, back);
  23151. }
  23152. if (this.front) {
  23153. front = this.front.clipPolygons(front);
  23154. }
  23155. if (this.back) {
  23156. back = this.back.clipPolygons(back);
  23157. }
  23158. else {
  23159. back = [];
  23160. }
  23161. return front.concat(back);
  23162. };
  23163. // Remove all polygons in this BSP tree that are inside the other BSP tree
  23164. // `bsp`.
  23165. Node.prototype.clipTo = function (bsp) {
  23166. this.polygons = bsp.clipPolygons(this.polygons);
  23167. if (this.front)
  23168. this.front.clipTo(bsp);
  23169. if (this.back)
  23170. this.back.clipTo(bsp);
  23171. };
  23172. // Return a list of all polygons in this BSP tree.
  23173. Node.prototype.allPolygons = function () {
  23174. var polygons = this.polygons.slice();
  23175. if (this.front)
  23176. polygons = polygons.concat(this.front.allPolygons());
  23177. if (this.back)
  23178. polygons = polygons.concat(this.back.allPolygons());
  23179. return polygons;
  23180. };
  23181. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  23182. // new polygons are filtered down to the bottom of the tree and become new
  23183. // nodes there. Each set of polygons is partitioned using the first polygon
  23184. // (no heuristic is used to pick a good split).
  23185. Node.prototype.build = function (polygons) {
  23186. if (!polygons.length)
  23187. return;
  23188. if (!this.plane)
  23189. this.plane = polygons[0].plane.clone();
  23190. var front = [], back = [];
  23191. for (var i = 0; i < polygons.length; i++) {
  23192. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  23193. }
  23194. if (front.length) {
  23195. if (!this.front)
  23196. this.front = new Node();
  23197. this.front.build(front);
  23198. }
  23199. if (back.length) {
  23200. if (!this.back)
  23201. this.back = new Node();
  23202. this.back.build(back);
  23203. }
  23204. };
  23205. return Node;
  23206. })();
  23207. var CSG = (function () {
  23208. function CSG() {
  23209. this.polygons = new Array();
  23210. }
  23211. // Convert BABYLON.Mesh to BABYLON.CSG
  23212. CSG.FromMesh = function (mesh) {
  23213. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  23214. if (mesh instanceof BABYLON.Mesh) {
  23215. mesh.computeWorldMatrix(true);
  23216. var matrix = mesh.getWorldMatrix();
  23217. var meshPosition = mesh.position.clone();
  23218. var meshRotation = mesh.rotation.clone();
  23219. var meshRotationQuaternion = mesh.rotationQuaternion.clone();
  23220. var meshScaling = mesh.scaling.clone();
  23221. }
  23222. else {
  23223. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  23224. }
  23225. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23226. var subMeshes = mesh.subMeshes;
  23227. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  23228. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  23229. vertices = [];
  23230. for (var j = 0; j < 3; j++) {
  23231. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  23232. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  23233. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  23234. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  23235. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  23236. vertex = new Vertex(position, normal, uv);
  23237. vertices.push(vertex);
  23238. }
  23239. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  23240. // To handle the case of degenerated triangle
  23241. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  23242. if (polygon.plane)
  23243. polygons.push(polygon);
  23244. }
  23245. }
  23246. var csg = CSG.FromPolygons(polygons);
  23247. csg.matrix = matrix;
  23248. csg.position = meshPosition;
  23249. csg.rotation = meshRotation;
  23250. csg.scaling = meshScaling;
  23251. csg.rotationQuaternion = meshRotationQuaternion;
  23252. currentCSGMeshId++;
  23253. return csg;
  23254. };
  23255. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  23256. CSG.FromPolygons = function (polygons) {
  23257. var csg = new BABYLON.CSG();
  23258. csg.polygons = polygons;
  23259. return csg;
  23260. };
  23261. CSG.prototype.clone = function () {
  23262. var csg = new BABYLON.CSG();
  23263. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  23264. csg.copyTransformAttributes(this);
  23265. return csg;
  23266. };
  23267. CSG.prototype.toPolygons = function () {
  23268. return this.polygons;
  23269. };
  23270. CSG.prototype.union = function (csg) {
  23271. var a = new Node(this.clone().polygons);
  23272. var b = new Node(csg.clone().polygons);
  23273. a.clipTo(b);
  23274. b.clipTo(a);
  23275. b.invert();
  23276. b.clipTo(a);
  23277. b.invert();
  23278. a.build(b.allPolygons());
  23279. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  23280. };
  23281. CSG.prototype.unionInPlace = function (csg) {
  23282. var a = new Node(this.polygons);
  23283. var b = new Node(csg.polygons);
  23284. a.clipTo(b);
  23285. b.clipTo(a);
  23286. b.invert();
  23287. b.clipTo(a);
  23288. b.invert();
  23289. a.build(b.allPolygons());
  23290. this.polygons = a.allPolygons();
  23291. };
  23292. CSG.prototype.subtract = function (csg) {
  23293. var a = new Node(this.clone().polygons);
  23294. var b = new Node(csg.clone().polygons);
  23295. a.invert();
  23296. a.clipTo(b);
  23297. b.clipTo(a);
  23298. b.invert();
  23299. b.clipTo(a);
  23300. b.invert();
  23301. a.build(b.allPolygons());
  23302. a.invert();
  23303. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  23304. };
  23305. CSG.prototype.subtractInPlace = function (csg) {
  23306. var a = new Node(this.polygons);
  23307. var b = new Node(csg.polygons);
  23308. a.invert();
  23309. a.clipTo(b);
  23310. b.clipTo(a);
  23311. b.invert();
  23312. b.clipTo(a);
  23313. b.invert();
  23314. a.build(b.allPolygons());
  23315. a.invert();
  23316. this.polygons = a.allPolygons();
  23317. };
  23318. CSG.prototype.intersect = function (csg) {
  23319. var a = new Node(this.clone().polygons);
  23320. var b = new Node(csg.clone().polygons);
  23321. a.invert();
  23322. b.clipTo(a);
  23323. b.invert();
  23324. a.clipTo(b);
  23325. b.clipTo(a);
  23326. a.build(b.allPolygons());
  23327. a.invert();
  23328. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  23329. };
  23330. CSG.prototype.intersectInPlace = function (csg) {
  23331. var a = new Node(this.polygons);
  23332. var b = new Node(csg.polygons);
  23333. a.invert();
  23334. b.clipTo(a);
  23335. b.invert();
  23336. a.clipTo(b);
  23337. b.clipTo(a);
  23338. a.build(b.allPolygons());
  23339. a.invert();
  23340. this.polygons = a.allPolygons();
  23341. };
  23342. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  23343. // not modified.
  23344. CSG.prototype.inverse = function () {
  23345. var csg = this.clone();
  23346. csg.inverseInPlace();
  23347. return csg;
  23348. };
  23349. CSG.prototype.inverseInPlace = function () {
  23350. this.polygons.map(function (p) {
  23351. p.flip();
  23352. });
  23353. };
  23354. // This is used to keep meshes transformations so they can be restored
  23355. // when we build back a Babylon Mesh
  23356. // NB : All CSG operations are performed in world coordinates
  23357. CSG.prototype.copyTransformAttributes = function (csg) {
  23358. this.matrix = csg.matrix;
  23359. this.position = csg.position;
  23360. this.rotation = csg.rotation;
  23361. this.scaling = csg.scaling;
  23362. this.rotationQuaternion = csg.rotationQuaternion;
  23363. return this;
  23364. };
  23365. // Build Raw mesh from CSG
  23366. // Coordinates here are in world space
  23367. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  23368. var matrix = this.matrix.clone();
  23369. matrix.invert();
  23370. 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;
  23371. if (keepSubMeshes) {
  23372. // Sort Polygons, since subMeshes are indices range
  23373. polygons.sort(function (a, b) {
  23374. if (a.shared.meshId === b.shared.meshId) {
  23375. return a.shared.subMeshId - b.shared.subMeshId;
  23376. }
  23377. else {
  23378. return a.shared.meshId - b.shared.meshId;
  23379. }
  23380. });
  23381. }
  23382. for (var i = 0, il = polygons.length; i < il; i++) {
  23383. polygon = polygons[i];
  23384. // Building SubMeshes
  23385. if (!subMesh_dict[polygon.shared.meshId]) {
  23386. subMesh_dict[polygon.shared.meshId] = {};
  23387. }
  23388. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  23389. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  23390. indexStart: +Infinity,
  23391. indexEnd: -Infinity,
  23392. materialIndex: polygon.shared.materialIndex
  23393. };
  23394. }
  23395. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  23396. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  23397. polygonIndices[0] = 0;
  23398. polygonIndices[1] = j - 1;
  23399. polygonIndices[2] = j;
  23400. for (var k = 0; k < 3; k++) {
  23401. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  23402. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  23403. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  23404. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  23405. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  23406. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  23407. // Check if 2 points can be merged
  23408. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  23409. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  23410. uvs.push(uv.x, uv.y);
  23411. normals.push(normal.x, normal.y, normal.z);
  23412. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  23413. }
  23414. indices.push(vertex_idx);
  23415. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  23416. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  23417. currentIndex++;
  23418. }
  23419. }
  23420. }
  23421. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  23422. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23423. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  23424. mesh.setIndices(indices);
  23425. if (keepSubMeshes) {
  23426. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  23427. var materialIndexOffset = 0, materialMaxIndex;
  23428. mesh.subMeshes.length = 0;
  23429. for (var m in subMesh_dict) {
  23430. materialMaxIndex = -1;
  23431. for (var sm in subMesh_dict[m]) {
  23432. subMesh_obj = subMesh_dict[m][sm];
  23433. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  23434. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  23435. }
  23436. materialIndexOffset += ++materialMaxIndex;
  23437. }
  23438. }
  23439. return mesh;
  23440. };
  23441. // Build Mesh from CSG taking material and transforms into account
  23442. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  23443. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  23444. mesh.material = material;
  23445. mesh.position.copyFrom(this.position);
  23446. mesh.rotation.copyFrom(this.rotation);
  23447. mesh.rotationQuaternion.copyFrom(this.rotationQuaternion);
  23448. mesh.scaling.copyFrom(this.scaling);
  23449. mesh.computeWorldMatrix(true);
  23450. return mesh;
  23451. };
  23452. return CSG;
  23453. })();
  23454. BABYLON.CSG = CSG;
  23455. })(BABYLON || (BABYLON = {}));
  23456. //# sourceMappingURL=babylon.csg.js.map
  23457. var __extends = this.__extends || function (d, b) {
  23458. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23459. function __() { this.constructor = d; }
  23460. __.prototype = b.prototype;
  23461. d.prototype = new __();
  23462. };
  23463. var BABYLON;
  23464. (function (BABYLON) {
  23465. var VRDistortionCorrectionPostProcess = (function (_super) {
  23466. __extends(VRDistortionCorrectionPostProcess, _super);
  23467. //ANY
  23468. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  23469. var _this = this;
  23470. _super.call(this, name, "vrDistortionCorrection", [
  23471. 'LensCenter',
  23472. 'Scale',
  23473. 'ScaleIn',
  23474. 'HmdWarpParam'
  23475. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  23476. this._isRightEye = isRightEye;
  23477. this._distortionFactors = vrMetrics.distortionK;
  23478. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  23479. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  23480. this.onSizeChanged = function () {
  23481. _this.aspectRatio = _this.width * .5 / _this.height;
  23482. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  23483. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  23484. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  23485. };
  23486. this.onApply = function (effect) {
  23487. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  23488. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  23489. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  23490. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  23491. };
  23492. }
  23493. return VRDistortionCorrectionPostProcess;
  23494. })(BABYLON.PostProcess);
  23495. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  23496. })(BABYLON || (BABYLON = {}));
  23497. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  23498. // Mainly based on these 2 articles :
  23499. // 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
  23500. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  23501. var BABYLON;
  23502. (function (BABYLON) {
  23503. (function (JoystickAxis) {
  23504. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  23505. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  23506. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  23507. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  23508. var JoystickAxis = BABYLON.JoystickAxis;
  23509. var VirtualJoystick = (function () {
  23510. function VirtualJoystick(leftJoystick) {
  23511. var _this = this;
  23512. if (leftJoystick) {
  23513. this._leftJoystick = true;
  23514. }
  23515. else {
  23516. this._leftJoystick = false;
  23517. }
  23518. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  23519. VirtualJoystick._globalJoystickIndex++;
  23520. // By default left & right arrow keys are moving the X
  23521. // and up & down keys are moving the Y
  23522. this._axisTargetedByLeftAndRight = 0 /* X */;
  23523. this._axisTargetedByUpAndDown = 1 /* Y */;
  23524. this.reverseLeftRight = false;
  23525. this.reverseUpDown = false;
  23526. // collections of pointers
  23527. this._touches = new BABYLON.SmartCollection();
  23528. this.deltaPosition = BABYLON.Vector3.Zero();
  23529. this._joystickSensibility = 25;
  23530. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  23531. this._rotationSpeed = 25;
  23532. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  23533. this._rotateOnAxisRelativeToMesh = false;
  23534. // injecting a canvas element on top of the canvas 3D game
  23535. if (!VirtualJoystick.vjCanvas) {
  23536. window.addEventListener("resize", function () {
  23537. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  23538. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  23539. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  23540. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  23541. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  23542. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  23543. }, false);
  23544. VirtualJoystick.vjCanvas = document.createElement("canvas");
  23545. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  23546. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  23547. VirtualJoystick.vjCanvas.width = window.innerWidth;
  23548. VirtualJoystick.vjCanvas.height = window.innerHeight;
  23549. VirtualJoystick.vjCanvas.style.width = "100%";
  23550. VirtualJoystick.vjCanvas.style.height = "100%";
  23551. VirtualJoystick.vjCanvas.style.position = "absolute";
  23552. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  23553. VirtualJoystick.vjCanvas.style.top = "0px";
  23554. VirtualJoystick.vjCanvas.style.left = "0px";
  23555. VirtualJoystick.vjCanvas.style.zIndex = "5";
  23556. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  23557. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  23558. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  23559. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  23560. document.body.appendChild(VirtualJoystick.vjCanvas);
  23561. }
  23562. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  23563. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  23564. this.pressed = false;
  23565. // default joystick color
  23566. this._joystickColor = "cyan";
  23567. this._joystickPointerID = -1;
  23568. // current joystick position
  23569. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  23570. // origin joystick position
  23571. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  23572. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  23573. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  23574. _this._onPointerDown(evt);
  23575. }, false);
  23576. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  23577. _this._onPointerMove(evt);
  23578. }, false);
  23579. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  23580. _this._onPointerUp(evt);
  23581. }, false);
  23582. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  23583. _this._onPointerUp(evt);
  23584. }, false);
  23585. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  23586. evt.preventDefault(); // Disables system menu
  23587. }, false);
  23588. requestAnimationFrame(function () {
  23589. _this._drawVirtualJoystick();
  23590. });
  23591. }
  23592. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  23593. this._joystickSensibility = newJoystickSensibility;
  23594. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  23595. };
  23596. VirtualJoystick.prototype._onPointerDown = function (e) {
  23597. var positionOnScreenCondition;
  23598. e.preventDefault();
  23599. if (this._leftJoystick === true) {
  23600. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  23601. }
  23602. else {
  23603. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  23604. }
  23605. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  23606. // First contact will be dedicated to the virtual joystick
  23607. this._joystickPointerID = e.pointerId;
  23608. this._joystickPointerStartPos.x = e.clientX;
  23609. this._joystickPointerStartPos.y = e.clientY;
  23610. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  23611. this._deltaJoystickVector.x = 0;
  23612. this._deltaJoystickVector.y = 0;
  23613. this.pressed = true;
  23614. this._touches.add(e.pointerId.toString(), e);
  23615. }
  23616. else {
  23617. // You can only trigger the action buttons with a joystick declared
  23618. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  23619. this._action();
  23620. this._touches.add(e.pointerId.toString(), e);
  23621. }
  23622. }
  23623. };
  23624. VirtualJoystick.prototype._onPointerMove = function (e) {
  23625. // If the current pointer is the one associated to the joystick (first touch contact)
  23626. if (this._joystickPointerID == e.pointerId) {
  23627. this._joystickPointerPos.x = e.clientX;
  23628. this._joystickPointerPos.y = e.clientY;
  23629. this._deltaJoystickVector = this._joystickPointerPos.clone();
  23630. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  23631. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  23632. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  23633. switch (this._axisTargetedByLeftAndRight) {
  23634. case 0 /* X */:
  23635. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  23636. break;
  23637. case 1 /* Y */:
  23638. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  23639. break;
  23640. case 2 /* Z */:
  23641. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  23642. break;
  23643. }
  23644. var directionUpDown = this.reverseUpDown ? 1 : -1;
  23645. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  23646. switch (this._axisTargetedByUpAndDown) {
  23647. case 0 /* X */:
  23648. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  23649. break;
  23650. case 1 /* Y */:
  23651. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  23652. break;
  23653. case 2 /* Z */:
  23654. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  23655. break;
  23656. }
  23657. }
  23658. else {
  23659. if (this._touches.item(e.pointerId.toString())) {
  23660. this._touches.item(e.pointerId.toString()).x = e.clientX;
  23661. this._touches.item(e.pointerId.toString()).y = e.clientY;
  23662. }
  23663. }
  23664. };
  23665. VirtualJoystick.prototype._onPointerUp = function (e) {
  23666. this._clearCanvas();
  23667. if (this._joystickPointerID == e.pointerId) {
  23668. this._joystickPointerID = -1;
  23669. this.pressed = false;
  23670. }
  23671. this._deltaJoystickVector.x = 0;
  23672. this._deltaJoystickVector.y = 0;
  23673. this._touches.remove(e.pointerId.toString());
  23674. };
  23675. /**
  23676. * Change the color of the virtual joystick
  23677. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  23678. */
  23679. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  23680. this._joystickColor = newColor;
  23681. };
  23682. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  23683. this._action = action;
  23684. };
  23685. // Define which axis you'd like to control for left & right
  23686. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  23687. switch (axis) {
  23688. case 0 /* X */:
  23689. case 1 /* Y */:
  23690. case 2 /* Z */:
  23691. this._axisTargetedByLeftAndRight = axis;
  23692. break;
  23693. default:
  23694. this._axisTargetedByLeftAndRight = 0 /* X */;
  23695. break;
  23696. }
  23697. };
  23698. // Define which axis you'd like to control for up & down
  23699. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  23700. switch (axis) {
  23701. case 0 /* X */:
  23702. case 1 /* Y */:
  23703. case 2 /* Z */:
  23704. this._axisTargetedByUpAndDown = axis;
  23705. break;
  23706. default:
  23707. this._axisTargetedByUpAndDown = 1 /* Y */;
  23708. break;
  23709. }
  23710. };
  23711. VirtualJoystick.prototype._clearCanvas = function () {
  23712. if (this._leftJoystick) {
  23713. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  23714. }
  23715. else {
  23716. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  23717. }
  23718. };
  23719. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  23720. var _this = this;
  23721. if (this.pressed) {
  23722. this._clearCanvas();
  23723. this._touches.forEach(function (touch) {
  23724. if (touch.pointerId === _this._joystickPointerID) {
  23725. VirtualJoystick.vjCanvasContext.beginPath();
  23726. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23727. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  23728. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  23729. VirtualJoystick.vjCanvasContext.stroke();
  23730. VirtualJoystick.vjCanvasContext.beginPath();
  23731. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23732. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  23733. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  23734. VirtualJoystick.vjCanvasContext.stroke();
  23735. VirtualJoystick.vjCanvasContext.beginPath();
  23736. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  23737. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  23738. VirtualJoystick.vjCanvasContext.stroke();
  23739. }
  23740. else {
  23741. VirtualJoystick.vjCanvasContext.beginPath();
  23742. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  23743. VirtualJoystick.vjCanvasContext.beginPath();
  23744. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  23745. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  23746. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  23747. VirtualJoystick.vjCanvasContext.stroke();
  23748. }
  23749. ;
  23750. });
  23751. }
  23752. requestAnimationFrame(function () {
  23753. _this._drawVirtualJoystick();
  23754. });
  23755. };
  23756. VirtualJoystick.prototype.releaseCanvas = function () {
  23757. if (VirtualJoystick.vjCanvas) {
  23758. document.body.removeChild(VirtualJoystick.vjCanvas);
  23759. VirtualJoystick.vjCanvas = null;
  23760. }
  23761. };
  23762. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  23763. VirtualJoystick._globalJoystickIndex = 0;
  23764. return VirtualJoystick;
  23765. })();
  23766. BABYLON.VirtualJoystick = VirtualJoystick;
  23767. })(BABYLON || (BABYLON = {}));
  23768. //# sourceMappingURL=babylon.virtualJoystick.js.map
  23769. var __extends = this.__extends || function (d, b) {
  23770. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23771. function __() { this.constructor = d; }
  23772. __.prototype = b.prototype;
  23773. d.prototype = new __();
  23774. };
  23775. var BABYLON;
  23776. (function (BABYLON) {
  23777. // We're mainly based on the logic defined into the FreeCamera code
  23778. var VirtualJoysticksCamera = (function (_super) {
  23779. __extends(VirtualJoysticksCamera, _super);
  23780. function VirtualJoysticksCamera(name, position, scene) {
  23781. _super.call(this, name, position, scene);
  23782. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  23783. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  23784. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  23785. this._leftjoystick.setJoystickSensibility(0.15);
  23786. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  23787. this._rightjoystick.setAxisForUpDown(0 /* X */);
  23788. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  23789. this._rightjoystick.reverseUpDown = true;
  23790. this._rightjoystick.setJoystickSensibility(0.05);
  23791. this._rightjoystick.setJoystickColor("yellow");
  23792. }
  23793. VirtualJoysticksCamera.prototype._checkInputs = function () {
  23794. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23795. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  23796. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23797. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  23798. if (!this._leftjoystick.pressed) {
  23799. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  23800. }
  23801. if (!this._rightjoystick.pressed) {
  23802. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  23803. }
  23804. _super.prototype._checkInputs.call(this);
  23805. };
  23806. VirtualJoysticksCamera.prototype.dispose = function () {
  23807. this._leftjoystick.releaseCanvas();
  23808. _super.prototype.dispose.call(this);
  23809. };
  23810. return VirtualJoysticksCamera;
  23811. })(BABYLON.FreeCamera);
  23812. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  23813. })(BABYLON || (BABYLON = {}));
  23814. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  23815. var __extends = this.__extends || function (d, b) {
  23816. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  23817. function __() { this.constructor = d; }
  23818. __.prototype = b.prototype;
  23819. d.prototype = new __();
  23820. };
  23821. var BABYLON;
  23822. (function (BABYLON) {
  23823. var ShaderMaterial = (function (_super) {
  23824. __extends(ShaderMaterial, _super);
  23825. function ShaderMaterial(name, scene, shaderPath, options) {
  23826. _super.call(this, name, scene);
  23827. this._textures = new Array();
  23828. this._floats = new Array();
  23829. this._floatsArrays = {};
  23830. this._colors3 = new Array();
  23831. this._colors4 = new Array();
  23832. this._vectors2 = new Array();
  23833. this._vectors3 = new Array();
  23834. this._matrices = new Array();
  23835. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  23836. this._shaderPath = shaderPath;
  23837. options.needAlphaBlending = options.needAlphaBlending || false;
  23838. options.needAlphaTesting = options.needAlphaTesting || false;
  23839. options.attributes = options.attributes || ["position", "normal", "uv"];
  23840. options.uniforms = options.uniforms || ["worldViewProjection"];
  23841. options.samplers = options.samplers || [];
  23842. this._options = options;
  23843. }
  23844. ShaderMaterial.prototype.needAlphaBlending = function () {
  23845. return this._options.needAlphaBlending;
  23846. };
  23847. ShaderMaterial.prototype.needAlphaTesting = function () {
  23848. return this._options.needAlphaTesting;
  23849. };
  23850. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  23851. if (this._options.uniforms.indexOf(uniformName) === -1) {
  23852. this._options.uniforms.push(uniformName);
  23853. }
  23854. };
  23855. ShaderMaterial.prototype.setTexture = function (name, texture) {
  23856. if (this._options.samplers.indexOf(name) === -1) {
  23857. this._options.samplers.push(name);
  23858. }
  23859. this._textures[name] = texture;
  23860. return this;
  23861. };
  23862. ShaderMaterial.prototype.setFloat = function (name, value) {
  23863. this._checkUniform(name);
  23864. this._floats[name] = value;
  23865. return this;
  23866. };
  23867. ShaderMaterial.prototype.setFloats = function (name, value) {
  23868. this._checkUniform(name);
  23869. this._floatsArrays[name] = value;
  23870. return this;
  23871. };
  23872. ShaderMaterial.prototype.setColor3 = function (name, value) {
  23873. this._checkUniform(name);
  23874. this._colors3[name] = value;
  23875. return this;
  23876. };
  23877. ShaderMaterial.prototype.setColor4 = function (name, value) {
  23878. this._checkUniform(name);
  23879. this._colors4[name] = value;
  23880. return this;
  23881. };
  23882. ShaderMaterial.prototype.setVector2 = function (name, value) {
  23883. this._checkUniform(name);
  23884. this._vectors2[name] = value;
  23885. return this;
  23886. };
  23887. ShaderMaterial.prototype.setVector3 = function (name, value) {
  23888. this._checkUniform(name);
  23889. this._vectors3[name] = value;
  23890. return this;
  23891. };
  23892. ShaderMaterial.prototype.setMatrix = function (name, value) {
  23893. this._checkUniform(name);
  23894. this._matrices[name] = value;
  23895. return this;
  23896. };
  23897. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  23898. var scene = this.getScene();
  23899. var engine = scene.getEngine();
  23900. if (!this.checkReadyOnEveryCall) {
  23901. if (this._renderId === scene.getRenderId()) {
  23902. return true;
  23903. }
  23904. }
  23905. // Instances
  23906. var defines = [];
  23907. var fallbacks = new BABYLON.EffectFallbacks();
  23908. if (useInstances) {
  23909. defines.push("#define INSTANCES");
  23910. }
  23911. // Bones
  23912. if (mesh && mesh.useBones) {
  23913. defines.push("#define BONES");
  23914. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23915. defines.push("#define BONES4");
  23916. fallbacks.addFallback(0, "BONES4");
  23917. }
  23918. // Alpha test
  23919. if (engine.getAlphaTesting()) {
  23920. defines.push("#define ALPHATEST");
  23921. }
  23922. var previousEffect = this._effect;
  23923. var join = defines.join("\n");
  23924. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  23925. if (!this._effect.isReady()) {
  23926. return false;
  23927. }
  23928. if (previousEffect !== this._effect) {
  23929. scene.resetCachedMaterial();
  23930. }
  23931. this._renderId = scene.getRenderId();
  23932. return true;
  23933. };
  23934. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23935. var scene = this.getScene();
  23936. if (this._options.uniforms.indexOf("world") !== -1) {
  23937. this._effect.setMatrix("world", world);
  23938. }
  23939. if (this._options.uniforms.indexOf("worldView") !== -1) {
  23940. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  23941. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  23942. }
  23943. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  23944. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  23945. }
  23946. };
  23947. ShaderMaterial.prototype.bind = function (world, mesh) {
  23948. // Std values
  23949. this.bindOnlyWorldMatrix(world);
  23950. if (this.getScene().getCachedMaterial() !== this) {
  23951. if (this._options.uniforms.indexOf("view") !== -1) {
  23952. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  23953. }
  23954. if (this._options.uniforms.indexOf("projection") !== -1) {
  23955. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  23956. }
  23957. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  23958. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23959. }
  23960. // Bones
  23961. if (mesh && mesh.useBones) {
  23962. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23963. }
  23964. for (var name in this._textures) {
  23965. this._effect.setTexture(name, this._textures[name]);
  23966. }
  23967. for (name in this._floats) {
  23968. this._effect.setFloat(name, this._floats[name]);
  23969. }
  23970. for (name in this._floatsArrays) {
  23971. this._effect.setArray(name, this._floatsArrays[name]);
  23972. }
  23973. for (name in this._colors3) {
  23974. this._effect.setColor3(name, this._colors3[name]);
  23975. }
  23976. for (name in this._colors4) {
  23977. var color = this._colors4[name];
  23978. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23979. }
  23980. for (name in this._vectors2) {
  23981. this._effect.setVector2(name, this._vectors2[name]);
  23982. }
  23983. for (name in this._vectors3) {
  23984. this._effect.setVector3(name, this._vectors3[name]);
  23985. }
  23986. for (name in this._matrices) {
  23987. this._effect.setMatrix(name, this._matrices[name]);
  23988. }
  23989. }
  23990. _super.prototype.bind.call(this, world, mesh);
  23991. };
  23992. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  23993. for (var name in this._textures) {
  23994. this._textures[name].dispose();
  23995. }
  23996. this._textures = [];
  23997. _super.prototype.dispose.call(this, forceDisposeEffect);
  23998. };
  23999. return ShaderMaterial;
  24000. })(BABYLON.Material);
  24001. BABYLON.ShaderMaterial = ShaderMaterial;
  24002. })(BABYLON || (BABYLON = {}));
  24003. //# sourceMappingURL=babylon.shaderMaterial.js.map
  24004. var BABYLON;
  24005. (function (BABYLON) {
  24006. var VertexData = (function () {
  24007. function VertexData() {
  24008. }
  24009. VertexData.prototype.set = function (data, kind) {
  24010. switch (kind) {
  24011. case BABYLON.VertexBuffer.PositionKind:
  24012. this.positions = data;
  24013. break;
  24014. case BABYLON.VertexBuffer.NormalKind:
  24015. this.normals = data;
  24016. break;
  24017. case BABYLON.VertexBuffer.UVKind:
  24018. this.uvs = data;
  24019. break;
  24020. case BABYLON.VertexBuffer.UV2Kind:
  24021. this.uv2s = data;
  24022. break;
  24023. case BABYLON.VertexBuffer.ColorKind:
  24024. this.colors = data;
  24025. break;
  24026. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24027. this.matricesIndices = data;
  24028. break;
  24029. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24030. this.matricesWeights = data;
  24031. break;
  24032. }
  24033. };
  24034. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24035. this._applyTo(mesh, updatable);
  24036. };
  24037. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24038. this._applyTo(geometry, updatable);
  24039. };
  24040. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24041. this._update(mesh);
  24042. };
  24043. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24044. this._update(geometry);
  24045. };
  24046. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24047. if (this.positions) {
  24048. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24049. }
  24050. if (this.normals) {
  24051. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24052. }
  24053. if (this.uvs) {
  24054. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24055. }
  24056. if (this.uv2s) {
  24057. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  24058. }
  24059. if (this.colors) {
  24060. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24061. }
  24062. if (this.matricesIndices) {
  24063. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24064. }
  24065. if (this.matricesWeights) {
  24066. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24067. }
  24068. if (this.indices) {
  24069. meshOrGeometry.setIndices(this.indices);
  24070. }
  24071. };
  24072. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24073. if (this.positions) {
  24074. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24075. }
  24076. if (this.normals) {
  24077. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24078. }
  24079. if (this.uvs) {
  24080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24081. }
  24082. if (this.uv2s) {
  24083. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  24084. }
  24085. if (this.colors) {
  24086. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24087. }
  24088. if (this.matricesIndices) {
  24089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24090. }
  24091. if (this.matricesWeights) {
  24092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24093. }
  24094. if (this.indices) {
  24095. meshOrGeometry.setIndices(this.indices);
  24096. }
  24097. };
  24098. VertexData.prototype.transform = function (matrix) {
  24099. var transformed = BABYLON.Vector3.Zero();
  24100. if (this.positions) {
  24101. var position = BABYLON.Vector3.Zero();
  24102. for (var index = 0; index < this.positions.length; index += 3) {
  24103. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24104. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24105. this.positions[index] = transformed.x;
  24106. this.positions[index + 1] = transformed.y;
  24107. this.positions[index + 2] = transformed.z;
  24108. }
  24109. }
  24110. if (this.normals) {
  24111. var normal = BABYLON.Vector3.Zero();
  24112. for (index = 0; index < this.normals.length; index += 3) {
  24113. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24114. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24115. this.normals[index] = transformed.x;
  24116. this.normals[index + 1] = transformed.y;
  24117. this.normals[index + 2] = transformed.z;
  24118. }
  24119. }
  24120. };
  24121. VertexData.prototype.merge = function (other) {
  24122. if (other.indices) {
  24123. if (!this.indices) {
  24124. this.indices = [];
  24125. }
  24126. var offset = this.positions ? this.positions.length / 3 : 0;
  24127. for (var index = 0; index < other.indices.length; index++) {
  24128. this.indices.push(other.indices[index] + offset);
  24129. }
  24130. }
  24131. if (other.positions) {
  24132. if (!this.positions) {
  24133. this.positions = [];
  24134. }
  24135. for (index = 0; index < other.positions.length; index++) {
  24136. this.positions.push(other.positions[index]);
  24137. }
  24138. }
  24139. if (other.normals) {
  24140. if (!this.normals) {
  24141. this.normals = [];
  24142. }
  24143. for (index = 0; index < other.normals.length; index++) {
  24144. this.normals.push(other.normals[index]);
  24145. }
  24146. }
  24147. if (other.uvs) {
  24148. if (!this.uvs) {
  24149. this.uvs = [];
  24150. }
  24151. for (index = 0; index < other.uvs.length; index++) {
  24152. this.uvs.push(other.uvs[index]);
  24153. }
  24154. }
  24155. if (other.uv2s) {
  24156. if (!this.uv2s) {
  24157. this.uv2s = [];
  24158. }
  24159. for (index = 0; index < other.uv2s.length; index++) {
  24160. this.uv2s.push(other.uv2s[index]);
  24161. }
  24162. }
  24163. if (other.matricesIndices) {
  24164. if (!this.matricesIndices) {
  24165. this.matricesIndices = [];
  24166. }
  24167. for (index = 0; index < other.matricesIndices.length; index++) {
  24168. this.matricesIndices.push(other.matricesIndices[index]);
  24169. }
  24170. }
  24171. if (other.matricesWeights) {
  24172. if (!this.matricesWeights) {
  24173. this.matricesWeights = [];
  24174. }
  24175. for (index = 0; index < other.matricesWeights.length; index++) {
  24176. this.matricesWeights.push(other.matricesWeights[index]);
  24177. }
  24178. }
  24179. if (other.colors) {
  24180. if (!this.colors) {
  24181. this.colors = [];
  24182. }
  24183. for (index = 0; index < other.colors.length; index++) {
  24184. this.colors.push(other.colors[index]);
  24185. }
  24186. }
  24187. };
  24188. // Statics
  24189. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24190. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24191. };
  24192. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24193. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24194. };
  24195. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24196. var result = new VertexData();
  24197. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24198. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24199. }
  24200. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24201. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24202. }
  24203. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24204. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24205. }
  24206. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24207. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24208. }
  24209. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24210. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24211. }
  24212. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24213. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24214. }
  24215. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24216. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24217. }
  24218. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24219. return result;
  24220. };
  24221. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  24222. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24223. closeArray = closeArray || false;
  24224. closePath = closePath || false;
  24225. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24226. offset = offset || defaultOffset;
  24227. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24228. var positions = [];
  24229. var indices = [];
  24230. var normals = [];
  24231. var uvs = [];
  24232. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24233. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24234. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24235. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24236. var minlg; // minimal length among all paths from pathArray
  24237. var lg = []; // array of path lengths : nb of vertex per path
  24238. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  24239. var p; // path iterator
  24240. var i; // point iterator
  24241. var j; // point iterator
  24242. // if single path in pathArray
  24243. if (pathArray.length < 2) {
  24244. var ar1 = [];
  24245. var ar2 = [];
  24246. for (i = 0; i < pathArray[0].length - offset; i++) {
  24247. ar1.push(pathArray[0][i]);
  24248. ar2.push(pathArray[0][i + offset]);
  24249. }
  24250. pathArray = [ar1, ar2];
  24251. }
  24252. // positions and horizontal distances (u)
  24253. var idc = 0;
  24254. minlg = pathArray[0].length;
  24255. for (p = 0; p < pathArray.length; p++) {
  24256. uTotalDistance[p] = 0;
  24257. us[p] = [0];
  24258. var path = pathArray[p];
  24259. var l = path.length;
  24260. minlg = (minlg < l) ? minlg : l;
  24261. lg[p] = l;
  24262. idx[p] = idc;
  24263. j = 0;
  24264. while (j < l) {
  24265. positions.push(path[j].x, path[j].y, path[j].z);
  24266. if (j > 0) {
  24267. var vectlg = path[j].subtract(path[j - 1]).length();
  24268. var dist = vectlg + uTotalDistance[p];
  24269. us[p].push(dist);
  24270. uTotalDistance[p] = dist;
  24271. }
  24272. j++;
  24273. }
  24274. if (closePath) {
  24275. vectlg = path[0].subtract(path[j - 1]).length();
  24276. dist = vectlg + uTotalDistance[p];
  24277. uTotalDistance[p] = dist;
  24278. }
  24279. idc += l;
  24280. }
  24281. for (i = 0; i < minlg; i++) {
  24282. vTotalDistance[i] = 0;
  24283. vs[i] = [0];
  24284. var path1;
  24285. var path2;
  24286. for (p = 0; p < pathArray.length - 1; p++) {
  24287. path1 = pathArray[p];
  24288. path2 = pathArray[p + 1];
  24289. vectlg = path2[i].subtract(path1[i]).length();
  24290. dist = vectlg + vTotalDistance[i];
  24291. vs[i].push(dist);
  24292. vTotalDistance[i] = dist;
  24293. }
  24294. if (closeArray) {
  24295. path1 = pathArray[p];
  24296. path2 = pathArray[0];
  24297. vectlg = path2[i].subtract(path1[i]).length();
  24298. dist = vectlg + vTotalDistance[i];
  24299. vTotalDistance[i] = dist;
  24300. }
  24301. }
  24302. // uvs
  24303. var u;
  24304. var v;
  24305. for (p = 0; p < pathArray.length; p++) {
  24306. for (i = 0; i < minlg; i++) {
  24307. u = us[p][i] / uTotalDistance[p];
  24308. v = vs[i][p] / vTotalDistance[i];
  24309. uvs.push(u, v);
  24310. }
  24311. }
  24312. // indices
  24313. p = 0; // path index
  24314. var pi = 0; // positions array index
  24315. var l1 = lg[p] - 1; // path1 length
  24316. var l2 = lg[p + 1] - 1; // path2 length
  24317. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24318. var shft = idx[1] - idx[0]; // shift
  24319. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  24320. var t1; // two consecutive triangles, so 4 points : point1
  24321. var t2; // point2
  24322. var t3; // point3
  24323. var t4; // point4
  24324. while (pi <= min && p < path1nb) {
  24325. // 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
  24326. t1 = pi;
  24327. t2 = pi + shft;
  24328. t3 = pi + 1;
  24329. t4 = pi + shft + 1;
  24330. indices.push(pi, pi + shft, pi + 1);
  24331. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24332. pi += 1;
  24333. if (pi === min) {
  24334. if (closePath) {
  24335. indices.push(pi, pi + shft, idx[p]);
  24336. indices.push(idx[p] + shft, idx[p], pi + shft);
  24337. t3 = idx[p];
  24338. t4 = idx[p] + shft;
  24339. }
  24340. p++;
  24341. if (p === lg.length - 1) {
  24342. shft = idx[0] - idx[p];
  24343. l1 = lg[p] - 1;
  24344. l2 = lg[0] - 1;
  24345. }
  24346. else {
  24347. shft = idx[p + 1] - idx[p];
  24348. l1 = lg[p] - 1;
  24349. l2 = lg[p + 1] - 1;
  24350. }
  24351. pi = idx[p];
  24352. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24353. }
  24354. }
  24355. // normals
  24356. VertexData.ComputeNormals(positions, indices, normals);
  24357. // sides
  24358. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24359. // Result
  24360. var vertexData = new VertexData();
  24361. vertexData.indices = indices;
  24362. vertexData.positions = positions;
  24363. vertexData.normals = normals;
  24364. vertexData.uvs = uvs;
  24365. return vertexData;
  24366. };
  24367. VertexData.CreateBox = function (size, sideOrientation) {
  24368. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24369. var normalsSource = [
  24370. new BABYLON.Vector3(0, 0, 1),
  24371. new BABYLON.Vector3(0, 0, -1),
  24372. new BABYLON.Vector3(1, 0, 0),
  24373. new BABYLON.Vector3(-1, 0, 0),
  24374. new BABYLON.Vector3(0, 1, 0),
  24375. new BABYLON.Vector3(0, -1, 0)
  24376. ];
  24377. var indices = [];
  24378. var positions = [];
  24379. var normals = [];
  24380. var uvs = [];
  24381. size = size || 1;
  24382. for (var index = 0; index < normalsSource.length; index++) {
  24383. var normal = normalsSource[index];
  24384. // Get two vectors perpendicular to the face normal and to each other.
  24385. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24386. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24387. // Six indices (two triangles) per face.
  24388. var verticesLength = positions.length / 3;
  24389. indices.push(verticesLength);
  24390. indices.push(verticesLength + 1);
  24391. indices.push(verticesLength + 2);
  24392. indices.push(verticesLength);
  24393. indices.push(verticesLength + 2);
  24394. indices.push(verticesLength + 3);
  24395. // Four vertices per face.
  24396. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  24397. positions.push(vertex.x, vertex.y, vertex.z);
  24398. normals.push(normal.x, normal.y, normal.z);
  24399. uvs.push(1.0, 1.0);
  24400. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  24401. positions.push(vertex.x, vertex.y, vertex.z);
  24402. normals.push(normal.x, normal.y, normal.z);
  24403. uvs.push(0.0, 1.0);
  24404. vertex = normal.add(side1).add(side2).scale(size / 2);
  24405. positions.push(vertex.x, vertex.y, vertex.z);
  24406. normals.push(normal.x, normal.y, normal.z);
  24407. uvs.push(0.0, 0.0);
  24408. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  24409. positions.push(vertex.x, vertex.y, vertex.z);
  24410. normals.push(normal.x, normal.y, normal.z);
  24411. uvs.push(1.0, 0.0);
  24412. }
  24413. // sides
  24414. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24415. // Result
  24416. var vertexData = new VertexData();
  24417. vertexData.indices = indices;
  24418. vertexData.positions = positions;
  24419. vertexData.normals = normals;
  24420. vertexData.uvs = uvs;
  24421. return vertexData;
  24422. };
  24423. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  24424. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24425. segments = segments || 32;
  24426. diameter = diameter || 1;
  24427. var radius = diameter / 2;
  24428. var totalZRotationSteps = 2 + segments;
  24429. var totalYRotationSteps = 2 * totalZRotationSteps;
  24430. var indices = [];
  24431. var positions = [];
  24432. var normals = [];
  24433. var uvs = [];
  24434. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24435. var normalizedZ = zRotationStep / totalZRotationSteps;
  24436. var angleZ = (normalizedZ * Math.PI);
  24437. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24438. var normalizedY = yRotationStep / totalYRotationSteps;
  24439. var angleY = normalizedY * Math.PI * 2;
  24440. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24441. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24442. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24443. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24444. var vertex = complete.scale(radius);
  24445. var normal = BABYLON.Vector3.Normalize(vertex);
  24446. positions.push(vertex.x, vertex.y, vertex.z);
  24447. normals.push(normal.x, normal.y, normal.z);
  24448. uvs.push(normalizedZ, normalizedY);
  24449. }
  24450. if (zRotationStep > 0) {
  24451. var verticesCount = positions.length / 3;
  24452. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24453. indices.push((firstIndex));
  24454. indices.push((firstIndex + 1));
  24455. indices.push(firstIndex + totalYRotationSteps + 1);
  24456. indices.push((firstIndex + totalYRotationSteps + 1));
  24457. indices.push((firstIndex + 1));
  24458. indices.push((firstIndex + totalYRotationSteps + 2));
  24459. }
  24460. }
  24461. }
  24462. // Sides
  24463. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24464. // Result
  24465. var vertexData = new VertexData();
  24466. vertexData.indices = indices;
  24467. vertexData.positions = positions;
  24468. vertexData.normals = normals;
  24469. vertexData.uvs = uvs;
  24470. return vertexData;
  24471. };
  24472. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  24473. if (subdivisions === void 0) { subdivisions = 1; }
  24474. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24475. var radiusTop = diameterTop / 2;
  24476. var radiusBottom = diameterBottom / 2;
  24477. var indices = [];
  24478. var positions = [];
  24479. var normals = [];
  24480. var uvs = [];
  24481. height = height || 1;
  24482. diameterTop = diameterTop || 0.5;
  24483. diameterBottom = diameterBottom || 1;
  24484. tessellation = tessellation || 16;
  24485. subdivisions = subdivisions || 1;
  24486. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  24487. var getCircleVector = function (i) {
  24488. var angle = (i * 2.0 * Math.PI / tessellation);
  24489. var dx = Math.cos(angle);
  24490. var dz = Math.sin(angle);
  24491. return new BABYLON.Vector3(dx, 0, dz);
  24492. };
  24493. var createCylinderCap = function (isTop) {
  24494. var radius = isTop ? radiusTop : radiusBottom;
  24495. if (radius === 0) {
  24496. return;
  24497. }
  24498. var vbase = positions.length / 3;
  24499. var offset = new BABYLON.Vector3(0, height / 2, 0);
  24500. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24501. if (!isTop) {
  24502. offset.scaleInPlace(-1);
  24503. textureScale.x = -textureScale.x;
  24504. }
  24505. for (var i = 0; i < tessellation; i++) {
  24506. var circleVector = getCircleVector(i);
  24507. var position = circleVector.scale(radius).add(offset);
  24508. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  24509. positions.push(position.x, position.y, position.z);
  24510. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24511. }
  24512. for (i = 0; i < tessellation - 2; i++) {
  24513. if (!isTop) {
  24514. indices.push(vbase);
  24515. indices.push(vbase + (i + 2) % tessellation);
  24516. indices.push(vbase + (i + 1) % tessellation);
  24517. }
  24518. else {
  24519. indices.push(vbase);
  24520. indices.push(vbase + (i + 1) % tessellation);
  24521. indices.push(vbase + (i + 2) % tessellation);
  24522. }
  24523. }
  24524. };
  24525. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  24526. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  24527. var stride = tessellation + 1;
  24528. for (var i = 0; i <= tessellation; i++) {
  24529. var circleVector = getCircleVector(i);
  24530. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  24531. var position, radius = radiusBottom;
  24532. for (var s = 0; s <= subdivisions; s++) {
  24533. // Update variables
  24534. position = circleVector.scale(radius);
  24535. position.addInPlace(base.add(offset.scale(s)));
  24536. textureCoordinate.y += 1 / subdivisions;
  24537. radius += (radiusTop - radiusBottom) / subdivisions;
  24538. // Push in arrays
  24539. positions.push(position.x, position.y, position.z);
  24540. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24541. }
  24542. }
  24543. subdivisions += 1;
  24544. for (s = 0; s < subdivisions - 1; s++) {
  24545. for (i = 0; i <= tessellation; i++) {
  24546. indices.push(i * subdivisions + s);
  24547. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  24548. indices.push(i * subdivisions + (s + 1));
  24549. indices.push(i * subdivisions + (s + 1));
  24550. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  24551. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  24552. }
  24553. }
  24554. // Create flat triangle fan caps to seal the top and bottom.
  24555. createCylinderCap(true);
  24556. createCylinderCap(false);
  24557. // Normals
  24558. VertexData.ComputeNormals(positions, indices, normals);
  24559. // Sides
  24560. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24561. // Result
  24562. var vertexData = new VertexData();
  24563. vertexData.indices = indices;
  24564. vertexData.positions = positions;
  24565. vertexData.normals = normals;
  24566. vertexData.uvs = uvs;
  24567. return vertexData;
  24568. };
  24569. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  24570. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24571. var indices = [];
  24572. var positions = [];
  24573. var normals = [];
  24574. var uvs = [];
  24575. diameter = diameter || 1;
  24576. thickness = thickness || 0.5;
  24577. tessellation = tessellation || 16;
  24578. var stride = tessellation + 1;
  24579. for (var i = 0; i <= tessellation; i++) {
  24580. var u = i / tessellation;
  24581. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24582. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24583. for (var j = 0; j <= tessellation; j++) {
  24584. var v = 1 - j / tessellation;
  24585. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24586. var dx = Math.cos(innerAngle);
  24587. var dy = Math.sin(innerAngle);
  24588. // Create a vertex.
  24589. var normal = new BABYLON.Vector3(dx, dy, 0);
  24590. var position = normal.scale(thickness / 2);
  24591. var textureCoordinate = new BABYLON.Vector2(u, v);
  24592. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24593. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24594. positions.push(position.x, position.y, position.z);
  24595. normals.push(normal.x, normal.y, normal.z);
  24596. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24597. // And create indices for two triangles.
  24598. var nextI = (i + 1) % stride;
  24599. var nextJ = (j + 1) % stride;
  24600. indices.push(i * stride + j);
  24601. indices.push(i * stride + nextJ);
  24602. indices.push(nextI * stride + j);
  24603. indices.push(i * stride + nextJ);
  24604. indices.push(nextI * stride + nextJ);
  24605. indices.push(nextI * stride + j);
  24606. }
  24607. }
  24608. // Sides
  24609. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24610. // Result
  24611. var vertexData = new VertexData();
  24612. vertexData.indices = indices;
  24613. vertexData.positions = positions;
  24614. vertexData.normals = normals;
  24615. vertexData.uvs = uvs;
  24616. return vertexData;
  24617. };
  24618. VertexData.CreateLines = function (points) {
  24619. var indices = [];
  24620. var positions = [];
  24621. for (var index = 0; index < points.length; index++) {
  24622. positions.push(points[index].x, points[index].y, points[index].z);
  24623. if (index > 0) {
  24624. indices.push(index - 1);
  24625. indices.push(index);
  24626. }
  24627. }
  24628. // Result
  24629. var vertexData = new VertexData();
  24630. vertexData.indices = indices;
  24631. vertexData.positions = positions;
  24632. return vertexData;
  24633. };
  24634. VertexData.CreateGround = function (width, height, subdivisions) {
  24635. var indices = [];
  24636. var positions = [];
  24637. var normals = [];
  24638. var uvs = [];
  24639. var row, col;
  24640. width = width || 1;
  24641. height = height || 1;
  24642. subdivisions = subdivisions || 1;
  24643. for (row = 0; row <= subdivisions; row++) {
  24644. for (col = 0; col <= subdivisions; col++) {
  24645. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24646. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24647. positions.push(position.x, position.y, position.z);
  24648. normals.push(normal.x, normal.y, normal.z);
  24649. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24650. }
  24651. }
  24652. for (row = 0; row < subdivisions; row++) {
  24653. for (col = 0; col < subdivisions; col++) {
  24654. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24655. indices.push(col + 1 + row * (subdivisions + 1));
  24656. indices.push(col + row * (subdivisions + 1));
  24657. indices.push(col + (row + 1) * (subdivisions + 1));
  24658. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24659. indices.push(col + row * (subdivisions + 1));
  24660. }
  24661. }
  24662. // Result
  24663. var vertexData = new VertexData();
  24664. vertexData.indices = indices;
  24665. vertexData.positions = positions;
  24666. vertexData.normals = normals;
  24667. vertexData.uvs = uvs;
  24668. return vertexData;
  24669. };
  24670. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  24671. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  24672. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  24673. var indices = [];
  24674. var positions = [];
  24675. var normals = [];
  24676. var uvs = [];
  24677. var row, col, tileRow, tileCol;
  24678. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  24679. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24680. precision.w = (precision.w < 1) ? 1 : precision.w;
  24681. precision.h = (precision.h < 1) ? 1 : precision.h;
  24682. var tileSize = {
  24683. 'w': (xmax - xmin) / subdivisions.w,
  24684. 'h': (zmax - zmin) / subdivisions.h
  24685. };
  24686. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24687. // Indices
  24688. var base = positions.length / 3;
  24689. var rowLength = precision.w + 1;
  24690. for (row = 0; row < precision.h; row++) {
  24691. for (col = 0; col < precision.w; col++) {
  24692. var square = [
  24693. base + col + row * rowLength,
  24694. base + (col + 1) + row * rowLength,
  24695. base + (col + 1) + (row + 1) * rowLength,
  24696. base + col + (row + 1) * rowLength
  24697. ];
  24698. indices.push(square[1]);
  24699. indices.push(square[2]);
  24700. indices.push(square[3]);
  24701. indices.push(square[0]);
  24702. indices.push(square[1]);
  24703. indices.push(square[3]);
  24704. }
  24705. }
  24706. // Position, normals and uvs
  24707. var position = BABYLON.Vector3.Zero();
  24708. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24709. for (row = 0; row <= precision.h; row++) {
  24710. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24711. for (col = 0; col <= precision.w; col++) {
  24712. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24713. position.y = 0;
  24714. positions.push(position.x, position.y, position.z);
  24715. normals.push(normal.x, normal.y, normal.z);
  24716. uvs.push(col / precision.w, row / precision.h);
  24717. }
  24718. }
  24719. }
  24720. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24721. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24722. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24723. }
  24724. }
  24725. // Result
  24726. var vertexData = new VertexData();
  24727. vertexData.indices = indices;
  24728. vertexData.positions = positions;
  24729. vertexData.normals = normals;
  24730. vertexData.uvs = uvs;
  24731. return vertexData;
  24732. };
  24733. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  24734. var indices = [];
  24735. var positions = [];
  24736. var normals = [];
  24737. var uvs = [];
  24738. var row, col;
  24739. for (row = 0; row <= subdivisions; row++) {
  24740. for (col = 0; col <= subdivisions; col++) {
  24741. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  24742. // Compute height
  24743. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  24744. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  24745. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  24746. var r = buffer[pos] / 255.0;
  24747. var g = buffer[pos + 1] / 255.0;
  24748. var b = buffer[pos + 2] / 255.0;
  24749. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  24750. position.y = minHeight + (maxHeight - minHeight) * gradient;
  24751. // Add vertex
  24752. positions.push(position.x, position.y, position.z);
  24753. normals.push(0, 0, 0);
  24754. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  24755. }
  24756. }
  24757. for (row = 0; row < subdivisions; row++) {
  24758. for (col = 0; col < subdivisions; col++) {
  24759. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24760. indices.push(col + 1 + row * (subdivisions + 1));
  24761. indices.push(col + row * (subdivisions + 1));
  24762. indices.push(col + (row + 1) * (subdivisions + 1));
  24763. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  24764. indices.push(col + row * (subdivisions + 1));
  24765. }
  24766. }
  24767. // Normals
  24768. VertexData.ComputeNormals(positions, indices, normals);
  24769. // Result
  24770. var vertexData = new VertexData();
  24771. vertexData.indices = indices;
  24772. vertexData.positions = positions;
  24773. vertexData.normals = normals;
  24774. vertexData.uvs = uvs;
  24775. return vertexData;
  24776. };
  24777. VertexData.CreatePlane = function (size, sideOrientation) {
  24778. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24779. var indices = [];
  24780. var positions = [];
  24781. var normals = [];
  24782. var uvs = [];
  24783. size = size || 1;
  24784. // Vertices
  24785. var halfSize = size / 2.0;
  24786. positions.push(-halfSize, -halfSize, 0);
  24787. normals.push(0, 0, -1.0);
  24788. uvs.push(0.0, 0.0);
  24789. positions.push(halfSize, -halfSize, 0);
  24790. normals.push(0, 0, -1.0);
  24791. uvs.push(1.0, 0.0);
  24792. positions.push(halfSize, halfSize, 0);
  24793. normals.push(0, 0, -1.0);
  24794. uvs.push(1.0, 1.0);
  24795. positions.push(-halfSize, halfSize, 0);
  24796. normals.push(0, 0, -1.0);
  24797. uvs.push(0.0, 1.0);
  24798. // Indices
  24799. indices.push(0);
  24800. indices.push(1);
  24801. indices.push(2);
  24802. indices.push(0);
  24803. indices.push(2);
  24804. indices.push(3);
  24805. // Sides
  24806. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24807. // Result
  24808. var vertexData = new VertexData();
  24809. vertexData.indices = indices;
  24810. vertexData.positions = positions;
  24811. vertexData.normals = normals;
  24812. vertexData.uvs = uvs;
  24813. return vertexData;
  24814. };
  24815. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  24816. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24817. var positions = [];
  24818. var indices = [];
  24819. var normals = [];
  24820. var uvs = [];
  24821. // positions and uvs
  24822. positions.push(0, 0, 0); // disc center first
  24823. uvs.push(0.5, 0.5);
  24824. var step = Math.PI * 2 / tessellation;
  24825. for (var a = 0; a < Math.PI * 2; a += step) {
  24826. var x = Math.cos(a);
  24827. var y = Math.sin(a);
  24828. var u = (x + 1) / 2;
  24829. var v = (1 - y) / 2;
  24830. positions.push(radius * x, radius * y, 0);
  24831. uvs.push(u, v);
  24832. }
  24833. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24834. uvs.push(uvs[2], uvs[3]);
  24835. //indices
  24836. var vertexNb = positions.length / 3;
  24837. for (var i = 1; i < vertexNb - 1; i++) {
  24838. indices.push(i + 1, 0, i);
  24839. }
  24840. // result
  24841. VertexData.ComputeNormals(positions, indices, normals);
  24842. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24843. var vertexData = new VertexData();
  24844. vertexData.indices = indices;
  24845. vertexData.positions = positions;
  24846. vertexData.normals = normals;
  24847. vertexData.uvs = uvs;
  24848. return vertexData;
  24849. };
  24850. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  24851. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  24852. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24853. var indices = [];
  24854. var positions = [];
  24855. var normals = [];
  24856. var uvs = [];
  24857. radius = radius || 2;
  24858. tube = tube || 0.5;
  24859. radialSegments = radialSegments || 32;
  24860. tubularSegments = tubularSegments || 32;
  24861. p = p || 2;
  24862. q = q || 3;
  24863. // Helper
  24864. var getPos = function (angle) {
  24865. var cu = Math.cos(angle);
  24866. var su = Math.sin(angle);
  24867. var quOverP = q / p * angle;
  24868. var cs = Math.cos(quOverP);
  24869. var tx = radius * (2 + cs) * 0.5 * cu;
  24870. var ty = radius * (2 + cs) * su * 0.5;
  24871. var tz = radius * Math.sin(quOverP) * 0.5;
  24872. return new BABYLON.Vector3(tx, ty, tz);
  24873. };
  24874. for (var i = 0; i <= radialSegments; i++) {
  24875. var modI = i % radialSegments;
  24876. var u = modI / radialSegments * 2 * p * Math.PI;
  24877. var p1 = getPos(u);
  24878. var p2 = getPos(u + 0.01);
  24879. var tang = p2.subtract(p1);
  24880. var n = p2.add(p1);
  24881. var bitan = BABYLON.Vector3.Cross(tang, n);
  24882. n = BABYLON.Vector3.Cross(bitan, tang);
  24883. bitan.normalize();
  24884. n.normalize();
  24885. for (var j = 0; j < tubularSegments; j++) {
  24886. var modJ = j % tubularSegments;
  24887. var v = modJ / tubularSegments * 2 * Math.PI;
  24888. var cx = -tube * Math.cos(v);
  24889. var cy = tube * Math.sin(v);
  24890. positions.push(p1.x + cx * n.x + cy * bitan.x);
  24891. positions.push(p1.y + cx * n.y + cy * bitan.y);
  24892. positions.push(p1.z + cx * n.z + cy * bitan.z);
  24893. uvs.push(i / radialSegments);
  24894. uvs.push(j / tubularSegments);
  24895. }
  24896. }
  24897. for (i = 0; i < radialSegments; i++) {
  24898. for (j = 0; j < tubularSegments; j++) {
  24899. var jNext = (j + 1) % tubularSegments;
  24900. var a = i * tubularSegments + j;
  24901. var b = (i + 1) * tubularSegments + j;
  24902. var c = (i + 1) * tubularSegments + jNext;
  24903. var d = i * tubularSegments + jNext;
  24904. indices.push(d);
  24905. indices.push(b);
  24906. indices.push(a);
  24907. indices.push(d);
  24908. indices.push(c);
  24909. indices.push(b);
  24910. }
  24911. }
  24912. // Normals
  24913. VertexData.ComputeNormals(positions, indices, normals);
  24914. // Sides
  24915. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24916. // Result
  24917. var vertexData = new VertexData();
  24918. vertexData.indices = indices;
  24919. vertexData.positions = positions;
  24920. vertexData.normals = normals;
  24921. vertexData.uvs = uvs;
  24922. return vertexData;
  24923. };
  24924. // Tools
  24925. /**
  24926. * @param {any} - positions (number[] or Float32Array)
  24927. * @param {any} - indices (number[] or Uint16Array)
  24928. * @param {any} - normals (number[] or Float32Array)
  24929. */
  24930. VertexData.ComputeNormals = function (positions, indices, normals) {
  24931. var index = 0;
  24932. // temp Vector3
  24933. var p1 = BABYLON.Vector3.Zero();
  24934. var p2 = BABYLON.Vector3.Zero();
  24935. var p3 = BABYLON.Vector3.Zero();
  24936. var p1p2 = BABYLON.Vector3.Zero();
  24937. var p3p2 = BABYLON.Vector3.Zero();
  24938. var faceNormal = BABYLON.Vector3.Zero();
  24939. var vertexNormali1 = BABYLON.Vector3.Zero();
  24940. var vertexNormali2 = BABYLON.Vector3.Zero();
  24941. var vertexNormali3 = BABYLON.Vector3.Zero();
  24942. // indice triplet = 1 face
  24943. var nbFaces = indices.length / 3;
  24944. for (index = 0; index < nbFaces; index++) {
  24945. var i1 = indices[index * 3];
  24946. var i2 = indices[index * 3 + 1];
  24947. var i3 = indices[index * 3 + 2];
  24948. // setting the temp V3
  24949. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  24950. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  24951. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  24952. p1.subtractToRef(p2, p1p2);
  24953. p3.subtractToRef(p2, p3p2);
  24954. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  24955. faceNormal.normalize();
  24956. // All intermediate results are stored in the normals array :
  24957. // get the normals at i1, i2 and i3 indexes
  24958. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  24959. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  24960. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  24961. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  24962. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  24963. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  24964. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  24965. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  24966. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  24967. // make intermediate vectors3 from normals values
  24968. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  24969. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  24970. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  24971. // add the current face normals to these intermediate vectors3
  24972. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  24973. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  24974. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  24975. // store back intermediate vectors3 into the normals array
  24976. normals[i1 * 3] = vertexNormali1.x;
  24977. normals[i1 * 3 + 1] = vertexNormali1.y;
  24978. normals[i1 * 3 + 2] = vertexNormali1.z;
  24979. normals[i2 * 3] = vertexNormali2.x;
  24980. normals[i2 * 3 + 1] = vertexNormali2.y;
  24981. normals[i2 * 3 + 2] = vertexNormali2.z;
  24982. normals[i3 * 3] = vertexNormali3.x;
  24983. normals[i3 * 3 + 1] = vertexNormali3.y;
  24984. normals[i3 * 3 + 2] = vertexNormali3.z;
  24985. }
  24986. for (index = 0; index < normals.length / 3; index++) {
  24987. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  24988. vertexNormali1.normalize();
  24989. normals[index * 3] = vertexNormali1.x;
  24990. normals[index * 3 + 1] = vertexNormali1.y;
  24991. normals[index * 3 + 2] = vertexNormali1.z;
  24992. }
  24993. };
  24994. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  24995. var li = indices.length;
  24996. var ln = normals.length;
  24997. var i;
  24998. var n;
  24999. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25000. switch (sideOrientation) {
  25001. case BABYLON.Mesh.FRONTSIDE:
  25002. break;
  25003. case BABYLON.Mesh.BACKSIDE:
  25004. var tmp;
  25005. for (i = 0; i < li; i += 3) {
  25006. tmp = indices[i];
  25007. indices[i] = indices[i + 2];
  25008. indices[i + 2] = tmp;
  25009. }
  25010. for (n = 0; n < ln; n++) {
  25011. normals[n] = -normals[n];
  25012. }
  25013. break;
  25014. case BABYLON.Mesh.DOUBLESIDE:
  25015. // positions
  25016. var lp = positions.length;
  25017. var l = lp / 3;
  25018. for (var p = 0; p < lp; p++) {
  25019. positions[lp + p] = positions[p];
  25020. }
  25021. for (i = 0; i < li; i += 3) {
  25022. indices[i + li] = indices[i + 2] + l;
  25023. indices[i + 1 + li] = indices[i + 1] + l;
  25024. indices[i + 2 + li] = indices[i] + l;
  25025. }
  25026. for (n = 0; n < ln; n++) {
  25027. normals[ln + n] = -normals[n];
  25028. }
  25029. // uvs
  25030. var lu = uvs.length;
  25031. for (var u = 0; u < lu; u++) {
  25032. uvs[u + lu] = uvs[u];
  25033. }
  25034. break;
  25035. }
  25036. };
  25037. return VertexData;
  25038. })();
  25039. BABYLON.VertexData = VertexData;
  25040. })(BABYLON || (BABYLON = {}));
  25041. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25042. var __extends = this.__extends || function (d, b) {
  25043. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25044. function __() { this.constructor = d; }
  25045. __.prototype = b.prototype;
  25046. d.prototype = new __();
  25047. };
  25048. var BABYLON;
  25049. (function (BABYLON) {
  25050. var AnaglyphFreeCamera = (function (_super) {
  25051. __extends(AnaglyphFreeCamera, _super);
  25052. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  25053. _super.call(this, name, position, scene);
  25054. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25055. }
  25056. return AnaglyphFreeCamera;
  25057. })(BABYLON.FreeCamera);
  25058. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  25059. var AnaglyphArcRotateCamera = (function (_super) {
  25060. __extends(AnaglyphArcRotateCamera, _super);
  25061. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  25062. _super.call(this, name, alpha, beta, radius, target, scene);
  25063. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25064. }
  25065. return AnaglyphArcRotateCamera;
  25066. })(BABYLON.ArcRotateCamera);
  25067. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  25068. })(BABYLON || (BABYLON = {}));
  25069. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  25070. var __extends = this.__extends || function (d, b) {
  25071. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25072. function __() { this.constructor = d; }
  25073. __.prototype = b.prototype;
  25074. d.prototype = new __();
  25075. };
  25076. var BABYLON;
  25077. (function (BABYLON) {
  25078. var AnaglyphPostProcess = (function (_super) {
  25079. __extends(AnaglyphPostProcess, _super);
  25080. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25081. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  25082. }
  25083. return AnaglyphPostProcess;
  25084. })(BABYLON.PostProcess);
  25085. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  25086. })(BABYLON || (BABYLON = {}));
  25087. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  25088. var BABYLON;
  25089. (function (BABYLON) {
  25090. var Tags = (function () {
  25091. function Tags() {
  25092. }
  25093. Tags.EnableFor = function (obj) {
  25094. obj._tags = obj._tags || {};
  25095. obj.hasTags = function () {
  25096. return Tags.HasTags(obj);
  25097. };
  25098. obj.addTags = function (tagsString) {
  25099. return Tags.AddTagsTo(obj, tagsString);
  25100. };
  25101. obj.removeTags = function (tagsString) {
  25102. return Tags.RemoveTagsFrom(obj, tagsString);
  25103. };
  25104. obj.matchesTagsQuery = function (tagsQuery) {
  25105. return Tags.MatchesQuery(obj, tagsQuery);
  25106. };
  25107. };
  25108. Tags.DisableFor = function (obj) {
  25109. delete obj._tags;
  25110. delete obj.hasTags;
  25111. delete obj.addTags;
  25112. delete obj.removeTags;
  25113. delete obj.matchesTagsQuery;
  25114. };
  25115. Tags.HasTags = function (obj) {
  25116. if (!obj._tags) {
  25117. return false;
  25118. }
  25119. return !BABYLON.Tools.IsEmpty(obj._tags);
  25120. };
  25121. Tags.GetTags = function (obj) {
  25122. if (!obj._tags) {
  25123. return null;
  25124. }
  25125. return obj._tags;
  25126. };
  25127. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25128. // a tag cannot start with '||', '&&', and '!'
  25129. // it cannot contain whitespaces
  25130. Tags.AddTagsTo = function (obj, tagsString) {
  25131. if (!tagsString) {
  25132. return;
  25133. }
  25134. var tags = tagsString.split(" ");
  25135. for (var t in tags) {
  25136. Tags._AddTagTo(obj, tags[t]);
  25137. }
  25138. };
  25139. Tags._AddTagTo = function (obj, tag) {
  25140. tag = tag.trim();
  25141. if (tag === "" || tag === "true" || tag === "false") {
  25142. return;
  25143. }
  25144. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25145. return;
  25146. }
  25147. Tags.EnableFor(obj);
  25148. obj._tags[tag] = true;
  25149. };
  25150. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25151. if (!Tags.HasTags(obj)) {
  25152. return;
  25153. }
  25154. var tags = tagsString.split(" ");
  25155. for (var t in tags) {
  25156. Tags._RemoveTagFrom(obj, tags[t]);
  25157. }
  25158. };
  25159. Tags._RemoveTagFrom = function (obj, tag) {
  25160. delete obj._tags[tag];
  25161. };
  25162. Tags.MatchesQuery = function (obj, tagsQuery) {
  25163. if (tagsQuery === undefined) {
  25164. return true;
  25165. }
  25166. if (tagsQuery === "") {
  25167. return Tags.HasTags(obj);
  25168. }
  25169. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25170. };
  25171. return Tags;
  25172. })();
  25173. BABYLON.Tags = Tags;
  25174. })(BABYLON || (BABYLON = {}));
  25175. //# sourceMappingURL=babylon.tags.js.map
  25176. var BABYLON;
  25177. (function (BABYLON) {
  25178. var Internals;
  25179. (function (Internals) {
  25180. var AndOrNotEvaluator = (function () {
  25181. function AndOrNotEvaluator() {
  25182. }
  25183. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25184. if (!query.match(/\([^\(\)]*\)/g)) {
  25185. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25186. }
  25187. else {
  25188. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25189. // remove parenthesis
  25190. r = r.slice(1, r.length - 1);
  25191. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25192. });
  25193. }
  25194. if (query === "true") {
  25195. return true;
  25196. }
  25197. if (query === "false") {
  25198. return false;
  25199. }
  25200. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25201. };
  25202. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25203. evaluateCallback = evaluateCallback || (function (r) {
  25204. return r === "true" ? true : false;
  25205. });
  25206. var result;
  25207. var or = parenthesisContent.split("||");
  25208. for (var i in or) {
  25209. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25210. var and = ori.split("&&");
  25211. if (and.length > 1) {
  25212. for (var j = 0; j < and.length; ++j) {
  25213. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25214. if (andj !== "true" && andj !== "false") {
  25215. if (andj[0] === "!") {
  25216. result = !evaluateCallback(andj.substring(1));
  25217. }
  25218. else {
  25219. result = evaluateCallback(andj);
  25220. }
  25221. }
  25222. else {
  25223. result = andj === "true" ? true : false;
  25224. }
  25225. if (!result) {
  25226. ori = "false";
  25227. break;
  25228. }
  25229. }
  25230. }
  25231. if (result || ori === "true") {
  25232. result = true;
  25233. break;
  25234. }
  25235. // result equals false (or undefined)
  25236. if (ori !== "true" && ori !== "false") {
  25237. if (ori[0] === "!") {
  25238. result = !evaluateCallback(ori.substring(1));
  25239. }
  25240. else {
  25241. result = evaluateCallback(ori);
  25242. }
  25243. }
  25244. else {
  25245. result = ori === "true" ? true : false;
  25246. }
  25247. }
  25248. // the whole parenthesis scope is replaced by 'true' or 'false'
  25249. return result ? "true" : "false";
  25250. };
  25251. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  25252. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  25253. // remove whitespaces
  25254. r = r.replace(/[\s]/g, function () { return ""; });
  25255. return r.length % 2 ? "!" : "";
  25256. });
  25257. booleanString = booleanString.trim();
  25258. if (booleanString === "!true") {
  25259. booleanString = "false";
  25260. }
  25261. else if (booleanString === "!false") {
  25262. booleanString = "true";
  25263. }
  25264. return booleanString;
  25265. };
  25266. return AndOrNotEvaluator;
  25267. })();
  25268. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  25269. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25270. })(BABYLON || (BABYLON = {}));
  25271. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  25272. var BABYLON;
  25273. (function (BABYLON) {
  25274. var PostProcessRenderPass = (function () {
  25275. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  25276. this._enabled = true;
  25277. this._refCount = 0;
  25278. this._name = name;
  25279. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  25280. this.setRenderList(renderList);
  25281. this._renderTexture.onBeforeRender = beforeRender;
  25282. this._renderTexture.onAfterRender = afterRender;
  25283. this._scene = scene;
  25284. this._renderList = renderList;
  25285. }
  25286. // private
  25287. PostProcessRenderPass.prototype._incRefCount = function () {
  25288. if (this._refCount === 0) {
  25289. this._scene.customRenderTargets.push(this._renderTexture);
  25290. }
  25291. return ++this._refCount;
  25292. };
  25293. PostProcessRenderPass.prototype._decRefCount = function () {
  25294. this._refCount--;
  25295. if (this._refCount <= 0) {
  25296. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  25297. }
  25298. return this._refCount;
  25299. };
  25300. PostProcessRenderPass.prototype._update = function () {
  25301. this.setRenderList(this._renderList);
  25302. };
  25303. // public
  25304. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  25305. this._renderTexture.renderList = renderList;
  25306. };
  25307. PostProcessRenderPass.prototype.getRenderTexture = function () {
  25308. return this._renderTexture;
  25309. };
  25310. return PostProcessRenderPass;
  25311. })();
  25312. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  25313. })(BABYLON || (BABYLON = {}));
  25314. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  25315. var BABYLON;
  25316. (function (BABYLON) {
  25317. var PostProcessRenderEffect = (function () {
  25318. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  25319. this._engine = engine;
  25320. this._name = name;
  25321. this._singleInstance = singleInstance || true;
  25322. this._getPostProcess = getPostProcess;
  25323. this._cameras = [];
  25324. this._indicesForCamera = [];
  25325. this._postProcesses = {};
  25326. this._renderPasses = {};
  25327. this._renderEffectAsPasses = {};
  25328. }
  25329. PostProcessRenderEffect.prototype._update = function () {
  25330. for (var renderPassName in this._renderPasses) {
  25331. this._renderPasses[renderPassName]._update();
  25332. }
  25333. };
  25334. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  25335. this._renderPasses[renderPass._name] = renderPass;
  25336. this._linkParameters();
  25337. };
  25338. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  25339. delete this._renderPasses[renderPass._name];
  25340. this._linkParameters();
  25341. };
  25342. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  25343. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  25344. this._linkParameters();
  25345. };
  25346. PostProcessRenderEffect.prototype.getPass = function (passName) {
  25347. for (var renderPassName in this._renderPasses) {
  25348. if (renderPassName === passName) {
  25349. return this._renderPasses[passName];
  25350. }
  25351. }
  25352. };
  25353. PostProcessRenderEffect.prototype.emptyPasses = function () {
  25354. this._renderPasses = {};
  25355. this._linkParameters();
  25356. };
  25357. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  25358. var cameraKey;
  25359. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25360. for (var i = 0; i < _cam.length; i++) {
  25361. var camera = _cam[i];
  25362. var cameraName = camera.name;
  25363. if (this._singleInstance) {
  25364. cameraKey = 0;
  25365. }
  25366. else {
  25367. cameraKey = cameraName;
  25368. }
  25369. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  25370. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  25371. if (!this._indicesForCamera[cameraName]) {
  25372. this._indicesForCamera[cameraName] = [];
  25373. }
  25374. this._indicesForCamera[cameraName].push(index);
  25375. if (this._cameras.indexOf(camera) === -1) {
  25376. this._cameras[cameraName] = camera;
  25377. }
  25378. for (var passName in this._renderPasses) {
  25379. this._renderPasses[passName]._incRefCount();
  25380. }
  25381. }
  25382. this._linkParameters();
  25383. };
  25384. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  25385. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25386. for (var i = 0; i < _cam.length; i++) {
  25387. var camera = _cam[i];
  25388. var cameraName = camera.name;
  25389. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25390. var index = this._cameras.indexOf(cameraName);
  25391. this._indicesForCamera.splice(index, 1);
  25392. this._cameras.splice(index, 1);
  25393. for (var passName in this._renderPasses) {
  25394. this._renderPasses[passName]._decRefCount();
  25395. }
  25396. }
  25397. };
  25398. PostProcessRenderEffect.prototype._enable = function (cameras) {
  25399. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25400. for (var i = 0; i < _cam.length; i++) {
  25401. var camera = _cam[i];
  25402. var cameraName = camera.name;
  25403. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  25404. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  25405. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  25406. }
  25407. }
  25408. for (var passName in this._renderPasses) {
  25409. this._renderPasses[passName]._incRefCount();
  25410. }
  25411. }
  25412. };
  25413. PostProcessRenderEffect.prototype._disable = function (cameras) {
  25414. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25415. for (var i = 0; i < _cam.length; i++) {
  25416. var camera = _cam[i];
  25417. var cameraName = camera.Name;
  25418. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  25419. for (var passName in this._renderPasses) {
  25420. this._renderPasses[passName]._decRefCount();
  25421. }
  25422. }
  25423. };
  25424. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  25425. if (this._singleInstance) {
  25426. return this._postProcesses[0];
  25427. }
  25428. else {
  25429. return this._postProcesses[camera.name];
  25430. }
  25431. };
  25432. PostProcessRenderEffect.prototype._linkParameters = function () {
  25433. var _this = this;
  25434. for (var index in this._postProcesses) {
  25435. if (this.applyParameters) {
  25436. this.applyParameters(this._postProcesses[index]);
  25437. }
  25438. this._postProcesses[index].onBeforeRender = function (effect) {
  25439. _this._linkTextures(effect);
  25440. };
  25441. }
  25442. };
  25443. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  25444. for (var renderPassName in this._renderPasses) {
  25445. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  25446. }
  25447. for (var renderEffectName in this._renderEffectAsPasses) {
  25448. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  25449. }
  25450. };
  25451. return PostProcessRenderEffect;
  25452. })();
  25453. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  25454. })(BABYLON || (BABYLON = {}));
  25455. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  25456. var BABYLON;
  25457. (function (BABYLON) {
  25458. var PostProcessRenderPipeline = (function () {
  25459. function PostProcessRenderPipeline(engine, name) {
  25460. this._engine = engine;
  25461. this._name = name;
  25462. this._renderEffects = {};
  25463. this._renderEffectsForIsolatedPass = {};
  25464. this._cameras = [];
  25465. }
  25466. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  25467. this._renderEffects[renderEffect._name] = renderEffect;
  25468. };
  25469. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  25470. var renderEffects = this._renderEffects[renderEffectName];
  25471. if (!renderEffects) {
  25472. return;
  25473. }
  25474. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25475. };
  25476. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  25477. var renderEffects = this._renderEffects[renderEffectName];
  25478. if (!renderEffects) {
  25479. return;
  25480. }
  25481. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  25482. };
  25483. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  25484. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25485. var indicesToDelete = [];
  25486. for (var i = 0; i < _cam.length; i++) {
  25487. var camera = _cam[i];
  25488. var cameraName = camera.name;
  25489. if (this._cameras.indexOf(camera) === -1) {
  25490. this._cameras[cameraName] = camera;
  25491. }
  25492. else if (unique) {
  25493. indicesToDelete.push(i);
  25494. }
  25495. }
  25496. for (var i = 0; i < indicesToDelete.length; i++) {
  25497. cameras.splice(indicesToDelete[i], 1);
  25498. }
  25499. for (var renderEffectName in this._renderEffects) {
  25500. this._renderEffects[renderEffectName]._attachCameras(_cam);
  25501. }
  25502. };
  25503. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  25504. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25505. for (var renderEffectName in this._renderEffects) {
  25506. this._renderEffects[renderEffectName]._detachCameras(_cam);
  25507. }
  25508. for (var i = 0; i < _cam.length; i++) {
  25509. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  25510. }
  25511. };
  25512. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  25513. var _this = this;
  25514. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25515. var pass = null;
  25516. for (var renderEffectName in this._renderEffects) {
  25517. pass = this._renderEffects[renderEffectName].getPass(passName);
  25518. if (pass != null) {
  25519. break;
  25520. }
  25521. }
  25522. if (pass === null) {
  25523. return;
  25524. }
  25525. for (var renderEffectName in this._renderEffects) {
  25526. this._renderEffects[renderEffectName]._disable(_cam);
  25527. }
  25528. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  25529. for (var i = 0; i < _cam.length; i++) {
  25530. var camera = _cam[i];
  25531. var cameraName = camera.name;
  25532. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  25533. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  25534. });
  25535. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  25536. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  25537. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  25538. }
  25539. };
  25540. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  25541. var _this = this;
  25542. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  25543. for (var i = 0; i < _cam.length; i++) {
  25544. var camera = _cam[i];
  25545. var cameraName = camera.name;
  25546. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  25547. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  25548. });
  25549. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  25550. }
  25551. for (var renderEffectName in this._renderEffects) {
  25552. this._renderEffects[renderEffectName]._enable(_cam);
  25553. }
  25554. };
  25555. PostProcessRenderPipeline.prototype._update = function () {
  25556. for (var renderEffectName in this._renderEffects) {
  25557. this._renderEffects[renderEffectName]._update();
  25558. }
  25559. for (var i = 0; i < this._cameras.length; i++) {
  25560. var cameraName = this._cameras[i].name;
  25561. if (this._renderEffectsForIsolatedPass[cameraName]) {
  25562. this._renderEffectsForIsolatedPass[cameraName]._update();
  25563. }
  25564. }
  25565. };
  25566. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  25567. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  25568. return PostProcessRenderPipeline;
  25569. })();
  25570. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  25571. })(BABYLON || (BABYLON = {}));
  25572. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  25573. var BABYLON;
  25574. (function (BABYLON) {
  25575. var PostProcessRenderPipelineManager = (function () {
  25576. function PostProcessRenderPipelineManager() {
  25577. this._renderPipelines = {};
  25578. }
  25579. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  25580. this._renderPipelines[renderPipeline._name] = renderPipeline;
  25581. };
  25582. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  25583. var renderPipeline = this._renderPipelines[renderPipelineName];
  25584. if (!renderPipeline) {
  25585. return;
  25586. }
  25587. renderPipeline._attachCameras(cameras, unique);
  25588. };
  25589. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  25590. var renderPipeline = this._renderPipelines[renderPipelineName];
  25591. if (!renderPipeline) {
  25592. return;
  25593. }
  25594. renderPipeline._detachCameras(cameras);
  25595. };
  25596. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25597. var renderPipeline = this._renderPipelines[renderPipelineName];
  25598. if (!renderPipeline) {
  25599. return;
  25600. }
  25601. renderPipeline._enableEffect(renderEffectName, cameras);
  25602. };
  25603. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  25604. var renderPipeline = this._renderPipelines[renderPipelineName];
  25605. if (!renderPipeline) {
  25606. return;
  25607. }
  25608. renderPipeline._disableEffect(renderEffectName, cameras);
  25609. };
  25610. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  25611. var renderPipeline = this._renderPipelines[renderPipelineName];
  25612. if (!renderPipeline) {
  25613. return;
  25614. }
  25615. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  25616. };
  25617. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  25618. var renderPipeline = this._renderPipelines[renderPipelineName];
  25619. if (!renderPipeline) {
  25620. return;
  25621. }
  25622. renderPipeline._disableDisplayOnlyPass(cameras);
  25623. };
  25624. PostProcessRenderPipelineManager.prototype.update = function () {
  25625. for (var renderPipelineName in this._renderPipelines) {
  25626. this._renderPipelines[renderPipelineName]._update();
  25627. }
  25628. };
  25629. return PostProcessRenderPipelineManager;
  25630. })();
  25631. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  25632. })(BABYLON || (BABYLON = {}));
  25633. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  25634. var __extends = this.__extends || function (d, b) {
  25635. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25636. function __() { this.constructor = d; }
  25637. __.prototype = b.prototype;
  25638. d.prototype = new __();
  25639. };
  25640. var BABYLON;
  25641. (function (BABYLON) {
  25642. var DisplayPassPostProcess = (function (_super) {
  25643. __extends(DisplayPassPostProcess, _super);
  25644. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25645. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  25646. }
  25647. return DisplayPassPostProcess;
  25648. })(BABYLON.PostProcess);
  25649. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  25650. })(BABYLON || (BABYLON = {}));
  25651. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  25652. var BABYLON;
  25653. (function (BABYLON) {
  25654. var BoundingBoxRenderer = (function () {
  25655. function BoundingBoxRenderer(scene) {
  25656. this.frontColor = new BABYLON.Color3(1, 1, 1);
  25657. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  25658. this.showBackLines = true;
  25659. this.renderList = new BABYLON.SmartArray(32);
  25660. this._scene = scene;
  25661. }
  25662. BoundingBoxRenderer.prototype._prepareRessources = function () {
  25663. if (this._colorShader) {
  25664. return;
  25665. }
  25666. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  25667. attributes: ["position"],
  25668. uniforms: ["worldViewProjection", "color"]
  25669. });
  25670. var engine = this._scene.getEngine();
  25671. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  25672. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  25673. 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]);
  25674. };
  25675. BoundingBoxRenderer.prototype.reset = function () {
  25676. this.renderList.reset();
  25677. };
  25678. BoundingBoxRenderer.prototype.render = function () {
  25679. if (this.renderList.length === 0) {
  25680. return;
  25681. }
  25682. this._prepareRessources();
  25683. if (!this._colorShader.isReady()) {
  25684. return;
  25685. }
  25686. var engine = this._scene.getEngine();
  25687. engine.setDepthWrite(false);
  25688. this._colorShader._preBind();
  25689. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  25690. var boundingBox = this.renderList.data[boundingBoxIndex];
  25691. var min = boundingBox.minimum;
  25692. var max = boundingBox.maximum;
  25693. var diff = max.subtract(min);
  25694. var median = min.add(diff.scale(0.5));
  25695. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  25696. // VBOs
  25697. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  25698. if (this.showBackLines) {
  25699. // Back
  25700. engine.setDepthFunctionToGreaterOrEqual();
  25701. this._scene.resetCachedMaterial();
  25702. this._colorShader.setColor4("color", this.backColor.toColor4());
  25703. this._colorShader.bind(worldMatrix);
  25704. // Draw order
  25705. engine.draw(false, 0, 24);
  25706. }
  25707. // Front
  25708. engine.setDepthFunctionToLess();
  25709. this._scene.resetCachedMaterial();
  25710. this._colorShader.setColor4("color", this.frontColor.toColor4());
  25711. this._colorShader.bind(worldMatrix);
  25712. // Draw order
  25713. engine.draw(false, 0, 24);
  25714. }
  25715. this._colorShader.unbind();
  25716. engine.setDepthFunctionToLessOrEqual();
  25717. engine.setDepthWrite(true);
  25718. };
  25719. BoundingBoxRenderer.prototype.dispose = function () {
  25720. if (!this._colorShader) {
  25721. return;
  25722. }
  25723. this._colorShader.dispose();
  25724. this._vb.dispose();
  25725. this._scene.getEngine()._releaseBuffer(this._ib);
  25726. };
  25727. return BoundingBoxRenderer;
  25728. })();
  25729. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  25730. })(BABYLON || (BABYLON = {}));
  25731. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  25732. var __extends = this.__extends || function (d, b) {
  25733. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  25734. function __() { this.constructor = d; }
  25735. __.prototype = b.prototype;
  25736. d.prototype = new __();
  25737. };
  25738. var BABYLON;
  25739. (function (BABYLON) {
  25740. var Condition = (function () {
  25741. function Condition(actionManager) {
  25742. this._actionManager = actionManager;
  25743. }
  25744. Condition.prototype.isValid = function () {
  25745. return true;
  25746. };
  25747. Condition.prototype._getProperty = function (propertyPath) {
  25748. return this._actionManager._getProperty(propertyPath);
  25749. };
  25750. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  25751. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25752. };
  25753. return Condition;
  25754. })();
  25755. BABYLON.Condition = Condition;
  25756. var ValueCondition = (function (_super) {
  25757. __extends(ValueCondition, _super);
  25758. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  25759. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  25760. _super.call(this, actionManager);
  25761. this.propertyPath = propertyPath;
  25762. this.value = value;
  25763. this.operator = operator;
  25764. this._target = this._getEffectiveTarget(target, this.propertyPath);
  25765. this._property = this._getProperty(this.propertyPath);
  25766. }
  25767. Object.defineProperty(ValueCondition, "IsEqual", {
  25768. get: function () {
  25769. return ValueCondition._IsEqual;
  25770. },
  25771. enumerable: true,
  25772. configurable: true
  25773. });
  25774. Object.defineProperty(ValueCondition, "IsDifferent", {
  25775. get: function () {
  25776. return ValueCondition._IsDifferent;
  25777. },
  25778. enumerable: true,
  25779. configurable: true
  25780. });
  25781. Object.defineProperty(ValueCondition, "IsGreater", {
  25782. get: function () {
  25783. return ValueCondition._IsGreater;
  25784. },
  25785. enumerable: true,
  25786. configurable: true
  25787. });
  25788. Object.defineProperty(ValueCondition, "IsLesser", {
  25789. get: function () {
  25790. return ValueCondition._IsLesser;
  25791. },
  25792. enumerable: true,
  25793. configurable: true
  25794. });
  25795. // Methods
  25796. ValueCondition.prototype.isValid = function () {
  25797. switch (this.operator) {
  25798. case ValueCondition.IsGreater:
  25799. return this._target[this._property] > this.value;
  25800. case ValueCondition.IsLesser:
  25801. return this._target[this._property] < this.value;
  25802. case ValueCondition.IsEqual:
  25803. case ValueCondition.IsDifferent:
  25804. var check;
  25805. if (this.value.equals) {
  25806. check = this.value.equals(this._target[this._property]);
  25807. }
  25808. else {
  25809. check = this.value === this._target[this._property];
  25810. }
  25811. return this.operator === ValueCondition.IsEqual ? check : !check;
  25812. }
  25813. return false;
  25814. };
  25815. // Statics
  25816. ValueCondition._IsEqual = 0;
  25817. ValueCondition._IsDifferent = 1;
  25818. ValueCondition._IsGreater = 2;
  25819. ValueCondition._IsLesser = 3;
  25820. return ValueCondition;
  25821. })(Condition);
  25822. BABYLON.ValueCondition = ValueCondition;
  25823. var PredicateCondition = (function (_super) {
  25824. __extends(PredicateCondition, _super);
  25825. function PredicateCondition(actionManager, predicate) {
  25826. _super.call(this, actionManager);
  25827. this.predicate = predicate;
  25828. }
  25829. PredicateCondition.prototype.isValid = function () {
  25830. return this.predicate();
  25831. };
  25832. return PredicateCondition;
  25833. })(Condition);
  25834. BABYLON.PredicateCondition = PredicateCondition;
  25835. var StateCondition = (function (_super) {
  25836. __extends(StateCondition, _super);
  25837. function StateCondition(actionManager, target, value) {
  25838. _super.call(this, actionManager);
  25839. this.value = value;
  25840. this._target = target;
  25841. }
  25842. // Methods
  25843. StateCondition.prototype.isValid = function () {
  25844. return this._target.state === this.value;
  25845. };
  25846. return StateCondition;
  25847. })(Condition);
  25848. BABYLON.StateCondition = StateCondition;
  25849. })(BABYLON || (BABYLON = {}));
  25850. //# sourceMappingURL=babylon.condition.js.map
  25851. var BABYLON;
  25852. (function (BABYLON) {
  25853. var Action = (function () {
  25854. function Action(triggerOptions, condition) {
  25855. this.triggerOptions = triggerOptions;
  25856. if (triggerOptions.parameter) {
  25857. this.trigger = triggerOptions.trigger;
  25858. this._triggerParameter = triggerOptions.parameter;
  25859. }
  25860. else {
  25861. this.trigger = triggerOptions;
  25862. }
  25863. this._nextActiveAction = this;
  25864. this._condition = condition;
  25865. }
  25866. // Methods
  25867. Action.prototype._prepare = function () {
  25868. };
  25869. Action.prototype.getTriggerParameter = function () {
  25870. return this._triggerParameter;
  25871. };
  25872. Action.prototype._executeCurrent = function (evt) {
  25873. if (this._nextActiveAction._condition) {
  25874. var condition = this._nextActiveAction._condition;
  25875. var currentRenderId = this._actionManager.getScene().getRenderId();
  25876. // We cache the current evaluation for the current frame
  25877. if (condition._evaluationId === currentRenderId) {
  25878. if (!condition._currentResult) {
  25879. return;
  25880. }
  25881. }
  25882. else {
  25883. condition._evaluationId = currentRenderId;
  25884. if (!condition.isValid()) {
  25885. condition._currentResult = false;
  25886. return;
  25887. }
  25888. condition._currentResult = true;
  25889. }
  25890. }
  25891. this._nextActiveAction.execute(evt);
  25892. if (this._nextActiveAction._child) {
  25893. if (!this._nextActiveAction._child._actionManager) {
  25894. this._nextActiveAction._child._actionManager = this._actionManager;
  25895. }
  25896. this._nextActiveAction = this._nextActiveAction._child;
  25897. }
  25898. else {
  25899. this._nextActiveAction = this;
  25900. }
  25901. };
  25902. Action.prototype.execute = function (evt) {
  25903. };
  25904. Action.prototype.then = function (action) {
  25905. this._child = action;
  25906. action._actionManager = this._actionManager;
  25907. action._prepare();
  25908. return action;
  25909. };
  25910. Action.prototype._getProperty = function (propertyPath) {
  25911. return this._actionManager._getProperty(propertyPath);
  25912. };
  25913. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  25914. return this._actionManager._getEffectiveTarget(target, propertyPath);
  25915. };
  25916. return Action;
  25917. })();
  25918. BABYLON.Action = Action;
  25919. })(BABYLON || (BABYLON = {}));
  25920. //# sourceMappingURL=babylon.action.js.map
  25921. var BABYLON;
  25922. (function (BABYLON) {
  25923. /**
  25924. * ActionEvent is the event beint sent when an action is triggered.
  25925. */
  25926. var ActionEvent = (function () {
  25927. /**
  25928. * @constructor
  25929. * @param source The mesh that triggered the action.
  25930. * @param pointerX the X mouse cursor position at the time of the event
  25931. * @param pointerY the Y mouse cursor position at the time of the event
  25932. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  25933. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  25934. */
  25935. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  25936. this.source = source;
  25937. this.pointerX = pointerX;
  25938. this.pointerY = pointerY;
  25939. this.meshUnderPointer = meshUnderPointer;
  25940. this.sourceEvent = sourceEvent;
  25941. }
  25942. /**
  25943. * Helper function to auto-create an ActionEvent from a source mesh.
  25944. * @param source the source mesh that triggered the event
  25945. * @param evt {Event} The original (browser) event
  25946. */
  25947. ActionEvent.CreateNew = function (source, evt) {
  25948. var scene = source.getScene();
  25949. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25950. };
  25951. /**
  25952. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  25953. * @param scene the scene where the event occurred
  25954. * @param evt {Event} The original (browser) event
  25955. */
  25956. ActionEvent.CreateNewFromScene = function (scene, evt) {
  25957. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  25958. };
  25959. return ActionEvent;
  25960. })();
  25961. BABYLON.ActionEvent = ActionEvent;
  25962. /**
  25963. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  25964. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  25965. */
  25966. var ActionManager = (function () {
  25967. function ActionManager(scene) {
  25968. // Members
  25969. this.actions = new Array();
  25970. this._scene = scene;
  25971. scene._actionManagers.push(this);
  25972. }
  25973. Object.defineProperty(ActionManager, "NothingTrigger", {
  25974. get: function () {
  25975. return ActionManager._NothingTrigger;
  25976. },
  25977. enumerable: true,
  25978. configurable: true
  25979. });
  25980. Object.defineProperty(ActionManager, "OnPickTrigger", {
  25981. get: function () {
  25982. return ActionManager._OnPickTrigger;
  25983. },
  25984. enumerable: true,
  25985. configurable: true
  25986. });
  25987. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  25988. get: function () {
  25989. return ActionManager._OnLeftPickTrigger;
  25990. },
  25991. enumerable: true,
  25992. configurable: true
  25993. });
  25994. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  25995. get: function () {
  25996. return ActionManager._OnRightPickTrigger;
  25997. },
  25998. enumerable: true,
  25999. configurable: true
  26000. });
  26001. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26002. get: function () {
  26003. return ActionManager._OnCenterPickTrigger;
  26004. },
  26005. enumerable: true,
  26006. configurable: true
  26007. });
  26008. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26009. get: function () {
  26010. return ActionManager._OnPointerOverTrigger;
  26011. },
  26012. enumerable: true,
  26013. configurable: true
  26014. });
  26015. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26016. get: function () {
  26017. return ActionManager._OnPointerOutTrigger;
  26018. },
  26019. enumerable: true,
  26020. configurable: true
  26021. });
  26022. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26023. get: function () {
  26024. return ActionManager._OnEveryFrameTrigger;
  26025. },
  26026. enumerable: true,
  26027. configurable: true
  26028. });
  26029. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26030. get: function () {
  26031. return ActionManager._OnIntersectionEnterTrigger;
  26032. },
  26033. enumerable: true,
  26034. configurable: true
  26035. });
  26036. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26037. get: function () {
  26038. return ActionManager._OnIntersectionExitTrigger;
  26039. },
  26040. enumerable: true,
  26041. configurable: true
  26042. });
  26043. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26044. get: function () {
  26045. return ActionManager._OnKeyDownTrigger;
  26046. },
  26047. enumerable: true,
  26048. configurable: true
  26049. });
  26050. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26051. get: function () {
  26052. return ActionManager._OnKeyUpTrigger;
  26053. },
  26054. enumerable: true,
  26055. configurable: true
  26056. });
  26057. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26058. get: function () {
  26059. return ActionManager._OnPickUpTrigger;
  26060. },
  26061. enumerable: true,
  26062. configurable: true
  26063. });
  26064. // Methods
  26065. ActionManager.prototype.dispose = function () {
  26066. var index = this._scene._actionManagers.indexOf(this);
  26067. if (index > -1) {
  26068. this._scene._actionManagers.splice(index, 1);
  26069. }
  26070. };
  26071. ActionManager.prototype.getScene = function () {
  26072. return this._scene;
  26073. };
  26074. /**
  26075. * Does this action manager handles actions of any of the given triggers
  26076. * @param {number[]} triggers - the triggers to be tested
  26077. * @return {boolean} whether one (or more) of the triggers is handeled
  26078. */
  26079. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26080. for (var index = 0; index < this.actions.length; index++) {
  26081. var action = this.actions[index];
  26082. if (triggers.indexOf(action.trigger) > -1) {
  26083. return true;
  26084. }
  26085. }
  26086. return false;
  26087. };
  26088. /**
  26089. * Does this action manager handles actions of a given trigger
  26090. * @param {number} trigger - the trigger to be tested
  26091. * @return {boolean} whether the trigger is handeled
  26092. */
  26093. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26094. for (var index = 0; index < this.actions.length; index++) {
  26095. var action = this.actions[index];
  26096. if (action.trigger === trigger) {
  26097. return true;
  26098. }
  26099. }
  26100. return false;
  26101. };
  26102. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  26103. /**
  26104. * Does this action manager has pointer triggers
  26105. * @return {boolean} whether or not it has pointer triggers
  26106. */
  26107. get: function () {
  26108. for (var index = 0; index < this.actions.length; index++) {
  26109. var action = this.actions[index];
  26110. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26111. return true;
  26112. }
  26113. if (action.trigger == ActionManager._OnPickUpTrigger) {
  26114. return true;
  26115. }
  26116. }
  26117. return false;
  26118. },
  26119. enumerable: true,
  26120. configurable: true
  26121. });
  26122. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26123. /**
  26124. * Does this action manager has pick triggers
  26125. * @return {boolean} whether or not it has pick triggers
  26126. */
  26127. get: function () {
  26128. for (var index = 0; index < this.actions.length; index++) {
  26129. var action = this.actions[index];
  26130. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  26131. return true;
  26132. }
  26133. }
  26134. return false;
  26135. },
  26136. enumerable: true,
  26137. configurable: true
  26138. });
  26139. /**
  26140. * Registers an action to this action manager
  26141. * @param {BABYLON.Action} action - the action to be registered
  26142. * @return {BABYLON.Action} the action amended (prepared) after registration
  26143. */
  26144. ActionManager.prototype.registerAction = function (action) {
  26145. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26146. if (this.getScene().actionManager !== this) {
  26147. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26148. return null;
  26149. }
  26150. }
  26151. this.actions.push(action);
  26152. action._actionManager = this;
  26153. action._prepare();
  26154. return action;
  26155. };
  26156. /**
  26157. * Process a specific trigger
  26158. * @param {number} trigger - the trigger to process
  26159. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26160. */
  26161. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26162. for (var index = 0; index < this.actions.length; index++) {
  26163. var action = this.actions[index];
  26164. if (action.trigger === trigger) {
  26165. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  26166. var parameter = action.getTriggerParameter();
  26167. if (parameter) {
  26168. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26169. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26170. if (actualkey !== parameter.toLowerCase()) {
  26171. continue;
  26172. }
  26173. }
  26174. }
  26175. action._executeCurrent(evt);
  26176. }
  26177. }
  26178. };
  26179. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26180. var properties = propertyPath.split(".");
  26181. for (var index = 0; index < properties.length - 1; index++) {
  26182. target = target[properties[index]];
  26183. }
  26184. return target;
  26185. };
  26186. ActionManager.prototype._getProperty = function (propertyPath) {
  26187. var properties = propertyPath.split(".");
  26188. return properties[properties.length - 1];
  26189. };
  26190. // Statics
  26191. ActionManager._NothingTrigger = 0;
  26192. ActionManager._OnPickTrigger = 1;
  26193. ActionManager._OnLeftPickTrigger = 2;
  26194. ActionManager._OnRightPickTrigger = 3;
  26195. ActionManager._OnCenterPickTrigger = 4;
  26196. ActionManager._OnPointerOverTrigger = 5;
  26197. ActionManager._OnPointerOutTrigger = 6;
  26198. ActionManager._OnEveryFrameTrigger = 7;
  26199. ActionManager._OnIntersectionEnterTrigger = 8;
  26200. ActionManager._OnIntersectionExitTrigger = 9;
  26201. ActionManager._OnKeyDownTrigger = 10;
  26202. ActionManager._OnKeyUpTrigger = 11;
  26203. ActionManager._OnPickUpTrigger = 12;
  26204. return ActionManager;
  26205. })();
  26206. BABYLON.ActionManager = ActionManager;
  26207. })(BABYLON || (BABYLON = {}));
  26208. //# sourceMappingURL=babylon.actionManager.js.map
  26209. var __extends = this.__extends || function (d, b) {
  26210. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26211. function __() { this.constructor = d; }
  26212. __.prototype = b.prototype;
  26213. d.prototype = new __();
  26214. };
  26215. var BABYLON;
  26216. (function (BABYLON) {
  26217. var InterpolateValueAction = (function (_super) {
  26218. __extends(InterpolateValueAction, _super);
  26219. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  26220. if (duration === void 0) { duration = 1000; }
  26221. _super.call(this, triggerOptions, condition);
  26222. this.propertyPath = propertyPath;
  26223. this.value = value;
  26224. this.duration = duration;
  26225. this.stopOtherAnimations = stopOtherAnimations;
  26226. this._target = target;
  26227. }
  26228. InterpolateValueAction.prototype._prepare = function () {
  26229. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26230. this._property = this._getProperty(this.propertyPath);
  26231. };
  26232. InterpolateValueAction.prototype.execute = function () {
  26233. var scene = this._actionManager.getScene();
  26234. var keys = [
  26235. {
  26236. frame: 0,
  26237. value: this._target[this._property]
  26238. },
  26239. {
  26240. frame: 100,
  26241. value: this.value
  26242. }
  26243. ];
  26244. var dataType;
  26245. if (typeof this.value === "number") {
  26246. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26247. }
  26248. else if (this.value instanceof BABYLON.Color3) {
  26249. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26250. }
  26251. else if (this.value instanceof BABYLON.Vector3) {
  26252. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  26253. }
  26254. else if (this.value instanceof BABYLON.Matrix) {
  26255. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  26256. }
  26257. else if (this.value instanceof BABYLON.Quaternion) {
  26258. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  26259. }
  26260. else {
  26261. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  26262. return;
  26263. }
  26264. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  26265. animation.setKeys(keys);
  26266. if (this.stopOtherAnimations) {
  26267. scene.stopAnimation(this._target);
  26268. }
  26269. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  26270. };
  26271. return InterpolateValueAction;
  26272. })(BABYLON.Action);
  26273. BABYLON.InterpolateValueAction = InterpolateValueAction;
  26274. })(BABYLON || (BABYLON = {}));
  26275. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  26276. var __extends = this.__extends || function (d, b) {
  26277. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26278. function __() { this.constructor = d; }
  26279. __.prototype = b.prototype;
  26280. d.prototype = new __();
  26281. };
  26282. var BABYLON;
  26283. (function (BABYLON) {
  26284. var SwitchBooleanAction = (function (_super) {
  26285. __extends(SwitchBooleanAction, _super);
  26286. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  26287. _super.call(this, triggerOptions, condition);
  26288. this.propertyPath = propertyPath;
  26289. this._target = target;
  26290. }
  26291. SwitchBooleanAction.prototype._prepare = function () {
  26292. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26293. this._property = this._getProperty(this.propertyPath);
  26294. };
  26295. SwitchBooleanAction.prototype.execute = function () {
  26296. this._target[this._property] = !this._target[this._property];
  26297. };
  26298. return SwitchBooleanAction;
  26299. })(BABYLON.Action);
  26300. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  26301. var SetStateAction = (function (_super) {
  26302. __extends(SetStateAction, _super);
  26303. function SetStateAction(triggerOptions, target, value, condition) {
  26304. _super.call(this, triggerOptions, condition);
  26305. this.value = value;
  26306. this._target = target;
  26307. }
  26308. SetStateAction.prototype.execute = function () {
  26309. this._target.state = this.value;
  26310. };
  26311. return SetStateAction;
  26312. })(BABYLON.Action);
  26313. BABYLON.SetStateAction = SetStateAction;
  26314. var SetValueAction = (function (_super) {
  26315. __extends(SetValueAction, _super);
  26316. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  26317. _super.call(this, triggerOptions, condition);
  26318. this.propertyPath = propertyPath;
  26319. this.value = value;
  26320. this._target = target;
  26321. }
  26322. SetValueAction.prototype._prepare = function () {
  26323. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26324. this._property = this._getProperty(this.propertyPath);
  26325. };
  26326. SetValueAction.prototype.execute = function () {
  26327. this._target[this._property] = this.value;
  26328. };
  26329. return SetValueAction;
  26330. })(BABYLON.Action);
  26331. BABYLON.SetValueAction = SetValueAction;
  26332. var IncrementValueAction = (function (_super) {
  26333. __extends(IncrementValueAction, _super);
  26334. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  26335. _super.call(this, triggerOptions, condition);
  26336. this.propertyPath = propertyPath;
  26337. this.value = value;
  26338. this._target = target;
  26339. }
  26340. IncrementValueAction.prototype._prepare = function () {
  26341. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26342. this._property = this._getProperty(this.propertyPath);
  26343. if (typeof this._target[this._property] !== "number") {
  26344. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  26345. }
  26346. };
  26347. IncrementValueAction.prototype.execute = function () {
  26348. this._target[this._property] += this.value;
  26349. };
  26350. return IncrementValueAction;
  26351. })(BABYLON.Action);
  26352. BABYLON.IncrementValueAction = IncrementValueAction;
  26353. var PlayAnimationAction = (function (_super) {
  26354. __extends(PlayAnimationAction, _super);
  26355. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  26356. _super.call(this, triggerOptions, condition);
  26357. this.from = from;
  26358. this.to = to;
  26359. this.loop = loop;
  26360. this._target = target;
  26361. }
  26362. PlayAnimationAction.prototype._prepare = function () {
  26363. };
  26364. PlayAnimationAction.prototype.execute = function () {
  26365. var scene = this._actionManager.getScene();
  26366. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  26367. };
  26368. return PlayAnimationAction;
  26369. })(BABYLON.Action);
  26370. BABYLON.PlayAnimationAction = PlayAnimationAction;
  26371. var StopAnimationAction = (function (_super) {
  26372. __extends(StopAnimationAction, _super);
  26373. function StopAnimationAction(triggerOptions, target, condition) {
  26374. _super.call(this, triggerOptions, condition);
  26375. this._target = target;
  26376. }
  26377. StopAnimationAction.prototype._prepare = function () {
  26378. };
  26379. StopAnimationAction.prototype.execute = function () {
  26380. var scene = this._actionManager.getScene();
  26381. scene.stopAnimation(this._target);
  26382. };
  26383. return StopAnimationAction;
  26384. })(BABYLON.Action);
  26385. BABYLON.StopAnimationAction = StopAnimationAction;
  26386. var DoNothingAction = (function (_super) {
  26387. __extends(DoNothingAction, _super);
  26388. function DoNothingAction(triggerOptions, condition) {
  26389. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  26390. _super.call(this, triggerOptions, condition);
  26391. }
  26392. DoNothingAction.prototype.execute = function () {
  26393. };
  26394. return DoNothingAction;
  26395. })(BABYLON.Action);
  26396. BABYLON.DoNothingAction = DoNothingAction;
  26397. var CombineAction = (function (_super) {
  26398. __extends(CombineAction, _super);
  26399. function CombineAction(triggerOptions, children, condition) {
  26400. _super.call(this, triggerOptions, condition);
  26401. this.children = children;
  26402. }
  26403. CombineAction.prototype._prepare = function () {
  26404. for (var index = 0; index < this.children.length; index++) {
  26405. this.children[index]._actionManager = this._actionManager;
  26406. this.children[index]._prepare();
  26407. }
  26408. };
  26409. CombineAction.prototype.execute = function (evt) {
  26410. for (var index = 0; index < this.children.length; index++) {
  26411. this.children[index].execute(evt);
  26412. }
  26413. };
  26414. return CombineAction;
  26415. })(BABYLON.Action);
  26416. BABYLON.CombineAction = CombineAction;
  26417. var ExecuteCodeAction = (function (_super) {
  26418. __extends(ExecuteCodeAction, _super);
  26419. function ExecuteCodeAction(triggerOptions, func, condition) {
  26420. _super.call(this, triggerOptions, condition);
  26421. this.func = func;
  26422. }
  26423. ExecuteCodeAction.prototype.execute = function (evt) {
  26424. this.func(evt);
  26425. };
  26426. return ExecuteCodeAction;
  26427. })(BABYLON.Action);
  26428. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  26429. var SetParentAction = (function (_super) {
  26430. __extends(SetParentAction, _super);
  26431. function SetParentAction(triggerOptions, target, parent, condition) {
  26432. _super.call(this, triggerOptions, condition);
  26433. this._target = target;
  26434. this._parent = parent;
  26435. }
  26436. SetParentAction.prototype._prepare = function () {
  26437. };
  26438. SetParentAction.prototype.execute = function () {
  26439. if (this._target.parent === this._parent) {
  26440. return;
  26441. }
  26442. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  26443. invertParentWorldMatrix.invert();
  26444. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  26445. this._target.parent = this._parent;
  26446. };
  26447. return SetParentAction;
  26448. })(BABYLON.Action);
  26449. BABYLON.SetParentAction = SetParentAction;
  26450. var PlaySoundAction = (function (_super) {
  26451. __extends(PlaySoundAction, _super);
  26452. function PlaySoundAction(triggerOptions, sound, condition) {
  26453. _super.call(this, triggerOptions, condition);
  26454. this._sound = sound;
  26455. }
  26456. PlaySoundAction.prototype._prepare = function () {
  26457. };
  26458. PlaySoundAction.prototype.execute = function () {
  26459. if (this._sound !== undefined)
  26460. this._sound.play();
  26461. };
  26462. return PlaySoundAction;
  26463. })(BABYLON.Action);
  26464. BABYLON.PlaySoundAction = PlaySoundAction;
  26465. var StopSoundAction = (function (_super) {
  26466. __extends(StopSoundAction, _super);
  26467. function StopSoundAction(triggerOptions, sound, condition) {
  26468. _super.call(this, triggerOptions, condition);
  26469. this._sound = sound;
  26470. }
  26471. StopSoundAction.prototype._prepare = function () {
  26472. };
  26473. StopSoundAction.prototype.execute = function () {
  26474. if (this._sound !== undefined)
  26475. this._sound.stop();
  26476. };
  26477. return StopSoundAction;
  26478. })(BABYLON.Action);
  26479. BABYLON.StopSoundAction = StopSoundAction;
  26480. })(BABYLON || (BABYLON = {}));
  26481. //# sourceMappingURL=babylon.directActions.js.map
  26482. var __extends = this.__extends || function (d, b) {
  26483. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  26484. function __() { this.constructor = d; }
  26485. __.prototype = b.prototype;
  26486. d.prototype = new __();
  26487. };
  26488. var BABYLON;
  26489. (function (BABYLON) {
  26490. var Geometry = (function () {
  26491. function Geometry(id, scene, vertexData, updatable, mesh) {
  26492. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26493. this._totalVertices = 0;
  26494. this._indices = [];
  26495. this._isDisposed = false;
  26496. this.id = id;
  26497. this._engine = scene.getEngine();
  26498. this._meshes = [];
  26499. this._scene = scene;
  26500. // vertexData
  26501. if (vertexData) {
  26502. this.setAllVerticesData(vertexData, updatable);
  26503. }
  26504. else {
  26505. this._totalVertices = 0;
  26506. this._indices = [];
  26507. }
  26508. // applyToMesh
  26509. if (mesh) {
  26510. this.applyToMesh(mesh);
  26511. mesh.computeWorldMatrix(true);
  26512. }
  26513. }
  26514. Geometry.prototype.getScene = function () {
  26515. return this._scene;
  26516. };
  26517. Geometry.prototype.getEngine = function () {
  26518. return this._engine;
  26519. };
  26520. Geometry.prototype.isReady = function () {
  26521. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26522. };
  26523. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26524. vertexData.applyToGeometry(this, updatable);
  26525. this.notifyUpdate();
  26526. };
  26527. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26528. this._vertexBuffers = this._vertexBuffers || {};
  26529. if (this._vertexBuffers[kind]) {
  26530. this._vertexBuffers[kind].dispose();
  26531. }
  26532. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26533. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26534. stride = this._vertexBuffers[kind].getStrideSize();
  26535. this._totalVertices = data.length / stride;
  26536. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26537. var meshes = this._meshes;
  26538. var numOfMeshes = meshes.length;
  26539. for (var index = 0; index < numOfMeshes; index++) {
  26540. var mesh = meshes[index];
  26541. mesh._resetPointsArrayCache();
  26542. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26543. mesh._createGlobalSubMesh();
  26544. mesh.computeWorldMatrix(true);
  26545. }
  26546. }
  26547. this.notifyUpdate(kind);
  26548. };
  26549. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26550. var vertexBuffer = this.getVertexBuffer(kind);
  26551. if (!vertexBuffer) {
  26552. return;
  26553. }
  26554. vertexBuffer.updateDirectly(data, offset);
  26555. this.notifyUpdate(kind);
  26556. };
  26557. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26558. var vertexBuffer = this.getVertexBuffer(kind);
  26559. if (!vertexBuffer) {
  26560. return;
  26561. }
  26562. vertexBuffer.update(data);
  26563. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26564. var extend;
  26565. var stride = vertexBuffer.getStrideSize();
  26566. this._totalVertices = data.length / stride;
  26567. if (updateExtends) {
  26568. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  26569. }
  26570. var meshes = this._meshes;
  26571. var numOfMeshes = meshes.length;
  26572. for (var index = 0; index < numOfMeshes; index++) {
  26573. var mesh = meshes[index];
  26574. mesh._resetPointsArrayCache();
  26575. if (updateExtends) {
  26576. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26577. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26578. var subMesh = mesh.subMeshes[subIndex];
  26579. subMesh.refreshBoundingInfo();
  26580. }
  26581. }
  26582. }
  26583. }
  26584. this.notifyUpdate(kind);
  26585. };
  26586. Geometry.prototype.getTotalVertices = function () {
  26587. if (!this.isReady()) {
  26588. return 0;
  26589. }
  26590. return this._totalVertices;
  26591. };
  26592. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  26593. var vertexBuffer = this.getVertexBuffer(kind);
  26594. if (!vertexBuffer) {
  26595. return null;
  26596. }
  26597. var orig = vertexBuffer.getData();
  26598. if (!copyWhenShared || this._meshes.length === 1) {
  26599. return orig;
  26600. }
  26601. else {
  26602. var len = orig.length;
  26603. var copy = [];
  26604. for (var i = 0; i < len; i++) {
  26605. copy.push(orig[i]);
  26606. }
  26607. return copy;
  26608. }
  26609. };
  26610. Geometry.prototype.getVertexBuffer = function (kind) {
  26611. if (!this.isReady()) {
  26612. return null;
  26613. }
  26614. return this._vertexBuffers[kind];
  26615. };
  26616. Geometry.prototype.getVertexBuffers = function () {
  26617. if (!this.isReady()) {
  26618. return null;
  26619. }
  26620. return this._vertexBuffers;
  26621. };
  26622. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26623. if (!this._vertexBuffers) {
  26624. if (this._delayInfo) {
  26625. return this._delayInfo.indexOf(kind) !== -1;
  26626. }
  26627. return false;
  26628. }
  26629. return this._vertexBuffers[kind] !== undefined;
  26630. };
  26631. Geometry.prototype.getVerticesDataKinds = function () {
  26632. var result = [];
  26633. if (!this._vertexBuffers && this._delayInfo) {
  26634. for (var kind in this._delayInfo) {
  26635. result.push(kind);
  26636. }
  26637. }
  26638. else {
  26639. for (kind in this._vertexBuffers) {
  26640. result.push(kind);
  26641. }
  26642. }
  26643. return result;
  26644. };
  26645. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26646. if (this._indexBuffer) {
  26647. this._engine._releaseBuffer(this._indexBuffer);
  26648. }
  26649. this._indices = indices;
  26650. if (this._meshes.length !== 0 && this._indices) {
  26651. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26652. }
  26653. if (totalVertices !== undefined) {
  26654. this._totalVertices = totalVertices;
  26655. }
  26656. var meshes = this._meshes;
  26657. var numOfMeshes = meshes.length;
  26658. for (var index = 0; index < numOfMeshes; index++) {
  26659. meshes[index]._createGlobalSubMesh();
  26660. }
  26661. this.notifyUpdate();
  26662. };
  26663. Geometry.prototype.getTotalIndices = function () {
  26664. if (!this.isReady()) {
  26665. return 0;
  26666. }
  26667. return this._indices.length;
  26668. };
  26669. Geometry.prototype.getIndices = function (copyWhenShared) {
  26670. if (!this.isReady()) {
  26671. return null;
  26672. }
  26673. var orig = this._indices;
  26674. if (!copyWhenShared || this._meshes.length === 1) {
  26675. return orig;
  26676. }
  26677. else {
  26678. var len = orig.length;
  26679. var copy = [];
  26680. for (var i = 0; i < len; i++) {
  26681. copy.push(orig[i]);
  26682. }
  26683. return copy;
  26684. }
  26685. };
  26686. Geometry.prototype.getIndexBuffer = function () {
  26687. if (!this.isReady()) {
  26688. return null;
  26689. }
  26690. return this._indexBuffer;
  26691. };
  26692. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26693. var meshes = this._meshes;
  26694. var index = meshes.indexOf(mesh);
  26695. if (index === -1) {
  26696. return;
  26697. }
  26698. for (var kind in this._vertexBuffers) {
  26699. this._vertexBuffers[kind].dispose();
  26700. }
  26701. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  26702. this._indexBuffer = null;
  26703. }
  26704. meshes.splice(index, 1);
  26705. mesh._geometry = null;
  26706. if (meshes.length === 0 && shouldDispose) {
  26707. this.dispose();
  26708. }
  26709. };
  26710. Geometry.prototype.applyToMesh = function (mesh) {
  26711. if (mesh._geometry === this) {
  26712. return;
  26713. }
  26714. var previousGeometry = mesh._geometry;
  26715. if (previousGeometry) {
  26716. previousGeometry.releaseForMesh(mesh);
  26717. }
  26718. var meshes = this._meshes;
  26719. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26720. mesh._geometry = this;
  26721. this._scene.pushGeometry(this);
  26722. meshes.push(mesh);
  26723. if (this.isReady()) {
  26724. this._applyToMesh(mesh);
  26725. }
  26726. else {
  26727. mesh._boundingInfo = this._boundingInfo;
  26728. }
  26729. };
  26730. Geometry.prototype._applyToMesh = function (mesh) {
  26731. var numOfMeshes = this._meshes.length;
  26732. for (var kind in this._vertexBuffers) {
  26733. if (numOfMeshes === 1) {
  26734. this._vertexBuffers[kind].create();
  26735. }
  26736. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  26737. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26738. mesh._resetPointsArrayCache();
  26739. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  26740. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26741. mesh._createGlobalSubMesh();
  26742. //bounding info was just created again, world matrix should be applied again.
  26743. mesh._updateBoundingInfo();
  26744. }
  26745. }
  26746. // indexBuffer
  26747. if (numOfMeshes === 1 && this._indices) {
  26748. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26749. }
  26750. if (this._indexBuffer) {
  26751. this._indexBuffer.references = numOfMeshes;
  26752. }
  26753. };
  26754. Geometry.prototype.notifyUpdate = function (kind) {
  26755. if (this.onGeometryUpdated) {
  26756. this.onGeometryUpdated(this, kind);
  26757. }
  26758. };
  26759. Geometry.prototype.load = function (scene, onLoaded) {
  26760. var _this = this;
  26761. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26762. return;
  26763. }
  26764. if (this.isReady()) {
  26765. if (onLoaded) {
  26766. onLoaded();
  26767. }
  26768. return;
  26769. }
  26770. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26771. scene._addPendingData(this);
  26772. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26773. _this._delayLoadingFunction(JSON.parse(data), _this);
  26774. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26775. _this._delayInfo = [];
  26776. scene._removePendingData(_this);
  26777. var meshes = _this._meshes;
  26778. var numOfMeshes = meshes.length;
  26779. for (var index = 0; index < numOfMeshes; index++) {
  26780. _this._applyToMesh(meshes[index]);
  26781. }
  26782. if (onLoaded) {
  26783. onLoaded();
  26784. }
  26785. }, function () {
  26786. }, scene.database);
  26787. };
  26788. Geometry.prototype.isDisposed = function () {
  26789. return this._isDisposed;
  26790. };
  26791. Geometry.prototype.dispose = function () {
  26792. var meshes = this._meshes;
  26793. var numOfMeshes = meshes.length;
  26794. var index;
  26795. for (index = 0; index < numOfMeshes; index++) {
  26796. this.releaseForMesh(meshes[index]);
  26797. }
  26798. this._meshes = [];
  26799. for (var kind in this._vertexBuffers) {
  26800. this._vertexBuffers[kind].dispose();
  26801. }
  26802. this._vertexBuffers = [];
  26803. this._totalVertices = 0;
  26804. if (this._indexBuffer) {
  26805. this._engine._releaseBuffer(this._indexBuffer);
  26806. }
  26807. this._indexBuffer = null;
  26808. this._indices = [];
  26809. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26810. this.delayLoadingFile = null;
  26811. this._delayLoadingFunction = null;
  26812. this._delayInfo = [];
  26813. this._boundingInfo = null; // todo: .dispose()
  26814. this._scene.removeGeometry(this);
  26815. this._isDisposed = true;
  26816. };
  26817. Geometry.prototype.copy = function (id) {
  26818. var vertexData = new BABYLON.VertexData();
  26819. vertexData.indices = [];
  26820. var indices = this.getIndices();
  26821. for (var index = 0; index < indices.length; index++) {
  26822. vertexData.indices.push(indices[index]);
  26823. }
  26824. var updatable = false;
  26825. var stopChecking = false;
  26826. for (var kind in this._vertexBuffers) {
  26827. // using slice() to make a copy of the array and not just reference it
  26828. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  26829. if (!stopChecking) {
  26830. updatable = this.getVertexBuffer(kind).isUpdatable();
  26831. stopChecking = !updatable;
  26832. }
  26833. }
  26834. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26835. geometry.delayLoadState = this.delayLoadState;
  26836. geometry.delayLoadingFile = this.delayLoadingFile;
  26837. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26838. for (kind in this._delayInfo) {
  26839. geometry._delayInfo = geometry._delayInfo || [];
  26840. geometry._delayInfo.push(kind);
  26841. }
  26842. // Bounding info
  26843. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  26844. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26845. return geometry;
  26846. };
  26847. // Statics
  26848. Geometry.ExtractFromMesh = function (mesh, id) {
  26849. var geometry = mesh._geometry;
  26850. if (!geometry) {
  26851. return null;
  26852. }
  26853. return geometry.copy(id);
  26854. };
  26855. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26856. // be aware Math.random() could cause collisions
  26857. Geometry.RandomId = function () {
  26858. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  26859. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  26860. return v.toString(16);
  26861. });
  26862. };
  26863. return Geometry;
  26864. })();
  26865. BABYLON.Geometry = Geometry;
  26866. /////// Primitives //////////////////////////////////////////////
  26867. var Geometry;
  26868. (function (Geometry) {
  26869. var Primitives;
  26870. (function (Primitives) {
  26871. /// Abstract class
  26872. var _Primitive = (function (_super) {
  26873. __extends(_Primitive, _super);
  26874. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  26875. this._beingRegenerated = true;
  26876. this._canBeRegenerated = canBeRegenerated;
  26877. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  26878. this._beingRegenerated = false;
  26879. }
  26880. _Primitive.prototype.canBeRegenerated = function () {
  26881. return this._canBeRegenerated;
  26882. };
  26883. _Primitive.prototype.regenerate = function () {
  26884. if (!this._canBeRegenerated) {
  26885. return;
  26886. }
  26887. this._beingRegenerated = true;
  26888. this.setAllVerticesData(this._regenerateVertexData(), false);
  26889. this._beingRegenerated = false;
  26890. };
  26891. _Primitive.prototype.asNewGeometry = function (id) {
  26892. return _super.prototype.copy.call(this, id);
  26893. };
  26894. // overrides
  26895. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26896. if (!this._beingRegenerated) {
  26897. return;
  26898. }
  26899. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26900. };
  26901. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26902. if (!this._beingRegenerated) {
  26903. return;
  26904. }
  26905. _super.prototype.setVerticesData.call(this, kind, data, false);
  26906. };
  26907. // to override
  26908. // protected
  26909. _Primitive.prototype._regenerateVertexData = function () {
  26910. throw new Error("Abstract method");
  26911. };
  26912. _Primitive.prototype.copy = function (id) {
  26913. throw new Error("Must be overriden in sub-classes.");
  26914. };
  26915. return _Primitive;
  26916. })(Geometry);
  26917. Primitives._Primitive = _Primitive;
  26918. var Ribbon = (function (_super) {
  26919. __extends(Ribbon, _super);
  26920. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26921. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26922. this.pathArray = pathArray;
  26923. this.closeArray = closeArray;
  26924. this.closePath = closePath;
  26925. this.offset = offset;
  26926. this.side = side;
  26927. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26928. }
  26929. Ribbon.prototype._regenerateVertexData = function () {
  26930. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  26931. };
  26932. Ribbon.prototype.copy = function (id) {
  26933. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26934. };
  26935. return Ribbon;
  26936. })(_Primitive);
  26937. Primitives.Ribbon = Ribbon;
  26938. var Box = (function (_super) {
  26939. __extends(Box, _super);
  26940. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26941. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26942. this.size = size;
  26943. this.side = side;
  26944. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26945. }
  26946. Box.prototype._regenerateVertexData = function () {
  26947. return BABYLON.VertexData.CreateBox(this.size, this.side);
  26948. };
  26949. Box.prototype.copy = function (id) {
  26950. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26951. };
  26952. return Box;
  26953. })(_Primitive);
  26954. Primitives.Box = Box;
  26955. var Sphere = (function (_super) {
  26956. __extends(Sphere, _super);
  26957. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26958. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26959. this.segments = segments;
  26960. this.diameter = diameter;
  26961. this.side = side;
  26962. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26963. }
  26964. Sphere.prototype._regenerateVertexData = function () {
  26965. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  26966. };
  26967. Sphere.prototype.copy = function (id) {
  26968. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26969. };
  26970. return Sphere;
  26971. })(_Primitive);
  26972. Primitives.Sphere = Sphere;
  26973. var Cylinder = (function (_super) {
  26974. __extends(Cylinder, _super);
  26975. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26976. if (subdivisions === void 0) { subdivisions = 1; }
  26977. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26978. this.height = height;
  26979. this.diameterTop = diameterTop;
  26980. this.diameterBottom = diameterBottom;
  26981. this.tessellation = tessellation;
  26982. this.subdivisions = subdivisions;
  26983. this.side = side;
  26984. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  26985. }
  26986. Cylinder.prototype._regenerateVertexData = function () {
  26987. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  26988. };
  26989. Cylinder.prototype.copy = function (id) {
  26990. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26991. };
  26992. return Cylinder;
  26993. })(_Primitive);
  26994. Primitives.Cylinder = Cylinder;
  26995. var Torus = (function (_super) {
  26996. __extends(Torus, _super);
  26997. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26998. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26999. this.diameter = diameter;
  27000. this.thickness = thickness;
  27001. this.tessellation = tessellation;
  27002. this.side = side;
  27003. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27004. }
  27005. Torus.prototype._regenerateVertexData = function () {
  27006. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  27007. };
  27008. Torus.prototype.copy = function (id) {
  27009. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27010. };
  27011. return Torus;
  27012. })(_Primitive);
  27013. Primitives.Torus = Torus;
  27014. var Ground = (function (_super) {
  27015. __extends(Ground, _super);
  27016. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27017. this.width = width;
  27018. this.height = height;
  27019. this.subdivisions = subdivisions;
  27020. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27021. }
  27022. Ground.prototype._regenerateVertexData = function () {
  27023. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  27024. };
  27025. Ground.prototype.copy = function (id) {
  27026. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27027. };
  27028. return Ground;
  27029. })(_Primitive);
  27030. Primitives.Ground = Ground;
  27031. var TiledGround = (function (_super) {
  27032. __extends(TiledGround, _super);
  27033. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27034. this.xmin = xmin;
  27035. this.zmin = zmin;
  27036. this.xmax = xmax;
  27037. this.zmax = zmax;
  27038. this.subdivisions = subdivisions;
  27039. this.precision = precision;
  27040. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27041. }
  27042. TiledGround.prototype._regenerateVertexData = function () {
  27043. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  27044. };
  27045. TiledGround.prototype.copy = function (id) {
  27046. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27047. };
  27048. return TiledGround;
  27049. })(_Primitive);
  27050. Primitives.TiledGround = TiledGround;
  27051. var Plane = (function (_super) {
  27052. __extends(Plane, _super);
  27053. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27054. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27055. this.size = size;
  27056. this.side = side;
  27057. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27058. }
  27059. Plane.prototype._regenerateVertexData = function () {
  27060. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  27061. };
  27062. Plane.prototype.copy = function (id) {
  27063. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27064. };
  27065. return Plane;
  27066. })(_Primitive);
  27067. Primitives.Plane = Plane;
  27068. var TorusKnot = (function (_super) {
  27069. __extends(TorusKnot, _super);
  27070. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27071. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27072. this.radius = radius;
  27073. this.tube = tube;
  27074. this.radialSegments = radialSegments;
  27075. this.tubularSegments = tubularSegments;
  27076. this.p = p;
  27077. this.q = q;
  27078. this.side = side;
  27079. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27080. }
  27081. TorusKnot.prototype._regenerateVertexData = function () {
  27082. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  27083. };
  27084. TorusKnot.prototype.copy = function (id) {
  27085. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27086. };
  27087. return TorusKnot;
  27088. })(_Primitive);
  27089. Primitives.TorusKnot = TorusKnot;
  27090. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27091. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27092. })(BABYLON || (BABYLON = {}));
  27093. //# sourceMappingURL=babylon.geometry.js.map
  27094. var __extends = this.__extends || function (d, b) {
  27095. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27096. function __() { this.constructor = d; }
  27097. __.prototype = b.prototype;
  27098. d.prototype = new __();
  27099. };
  27100. var BABYLON;
  27101. (function (BABYLON) {
  27102. var GroundMesh = (function (_super) {
  27103. __extends(GroundMesh, _super);
  27104. function GroundMesh(name, scene) {
  27105. _super.call(this, name, scene);
  27106. this.generateOctree = false;
  27107. this._worldInverse = new BABYLON.Matrix();
  27108. }
  27109. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27110. get: function () {
  27111. return this._subdivisions;
  27112. },
  27113. enumerable: true,
  27114. configurable: true
  27115. });
  27116. GroundMesh.prototype.optimize = function (chunksCount) {
  27117. this.subdivide(this._subdivisions);
  27118. this.createOrUpdateSubmeshesOctree(32);
  27119. };
  27120. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27121. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  27122. this.getWorldMatrix().invertToRef(this._worldInverse);
  27123. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  27124. var pickInfo = this.intersects(ray);
  27125. if (pickInfo.hit) {
  27126. return pickInfo.pickedPoint.y;
  27127. }
  27128. return 0;
  27129. };
  27130. return GroundMesh;
  27131. })(BABYLON.Mesh);
  27132. BABYLON.GroundMesh = GroundMesh;
  27133. })(BABYLON || (BABYLON = {}));
  27134. //# sourceMappingURL=babylon.groundMesh.js.map
  27135. var __extends = this.__extends || function (d, b) {
  27136. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27137. function __() { this.constructor = d; }
  27138. __.prototype = b.prototype;
  27139. d.prototype = new __();
  27140. };
  27141. var BABYLON;
  27142. (function (BABYLON) {
  27143. var Gamepads = (function () {
  27144. function Gamepads(ongamedpadconnected) {
  27145. var _this = this;
  27146. this.babylonGamepads = [];
  27147. this.oneGamepadConnected = false;
  27148. this.isMonitoring = false;
  27149. this.gamepadEventSupported = 'GamepadEvent' in window;
  27150. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  27151. 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=";
  27152. this._callbackGamepadConnected = ongamedpadconnected;
  27153. if (this.gamepadSupportAvailable) {
  27154. // Checking if the gamepad connected event is supported (like in Firefox)
  27155. if (this.gamepadEventSupported) {
  27156. window.addEventListener('gamepadconnected', function (evt) {
  27157. _this._onGamepadConnected(evt);
  27158. }, false);
  27159. window.addEventListener('gamepaddisconnected', function (evt) {
  27160. _this._onGamepadDisconnected(evt);
  27161. }, false);
  27162. }
  27163. else {
  27164. this._startMonitoringGamepads();
  27165. }
  27166. if (!this.oneGamepadConnected) {
  27167. this._insertGamepadDOMInstructions();
  27168. }
  27169. }
  27170. else {
  27171. this._insertGamepadDOMNotSupported();
  27172. }
  27173. }
  27174. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  27175. Gamepads.gamepadDOMInfo = document.createElement("div");
  27176. var buttonAImage = document.createElement("img");
  27177. buttonAImage.src = this.buttonADataURL;
  27178. var spanMessage = document.createElement("span");
  27179. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  27180. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  27181. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  27182. Gamepads.gamepadDOMInfo.style.position = "absolute";
  27183. Gamepads.gamepadDOMInfo.style.width = "100%";
  27184. Gamepads.gamepadDOMInfo.style.height = "48px";
  27185. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  27186. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  27187. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  27188. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  27189. buttonAImage.style.position = "relative";
  27190. buttonAImage.style.bottom = "8px";
  27191. spanMessage.style.position = "relative";
  27192. spanMessage.style.fontSize = "32px";
  27193. spanMessage.style.bottom = "32px";
  27194. spanMessage.style.color = "green";
  27195. document.body.appendChild(Gamepads.gamepadDOMInfo);
  27196. };
  27197. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  27198. Gamepads.gamepadDOMInfo = document.createElement("div");
  27199. var spanMessage = document.createElement("span");
  27200. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  27201. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  27202. Gamepads.gamepadDOMInfo.style.position = "absolute";
  27203. Gamepads.gamepadDOMInfo.style.width = "100%";
  27204. Gamepads.gamepadDOMInfo.style.height = "40px";
  27205. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  27206. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  27207. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  27208. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  27209. spanMessage.style.position = "relative";
  27210. spanMessage.style.fontSize = "32px";
  27211. spanMessage.style.color = "red";
  27212. document.body.appendChild(Gamepads.gamepadDOMInfo);
  27213. };
  27214. Gamepads.prototype.dispose = function () {
  27215. if (Gamepads.gamepadDOMInfo) {
  27216. document.body.removeChild(Gamepads.gamepadDOMInfo);
  27217. }
  27218. };
  27219. Gamepads.prototype._onGamepadConnected = function (evt) {
  27220. var newGamepad = this._addNewGamepad(evt.gamepad);
  27221. if (this._callbackGamepadConnected)
  27222. this._callbackGamepadConnected(newGamepad);
  27223. this._startMonitoringGamepads();
  27224. };
  27225. Gamepads.prototype._addNewGamepad = function (gamepad) {
  27226. if (!this.oneGamepadConnected) {
  27227. this.oneGamepadConnected = true;
  27228. if (Gamepads.gamepadDOMInfo) {
  27229. document.body.removeChild(Gamepads.gamepadDOMInfo);
  27230. Gamepads.gamepadDOMInfo = null;
  27231. }
  27232. }
  27233. var newGamepad;
  27234. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  27235. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  27236. }
  27237. else {
  27238. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  27239. }
  27240. this.babylonGamepads.push(newGamepad);
  27241. return newGamepad;
  27242. };
  27243. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  27244. for (var i in this.babylonGamepads) {
  27245. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  27246. this.babylonGamepads.splice(i, 1);
  27247. break;
  27248. }
  27249. }
  27250. // If no gamepads are left, stop the polling loop.
  27251. if (this.babylonGamepads.length == 0) {
  27252. this._stopMonitoringGamepads();
  27253. }
  27254. };
  27255. Gamepads.prototype._startMonitoringGamepads = function () {
  27256. if (!this.isMonitoring) {
  27257. this.isMonitoring = true;
  27258. this._checkGamepadsStatus();
  27259. }
  27260. };
  27261. Gamepads.prototype._stopMonitoringGamepads = function () {
  27262. this.isMonitoring = false;
  27263. };
  27264. Gamepads.prototype._checkGamepadsStatus = function () {
  27265. var _this = this;
  27266. // updating gamepad objects
  27267. this._updateGamepadObjects();
  27268. for (var i in this.babylonGamepads) {
  27269. this.babylonGamepads[i].update();
  27270. }
  27271. if (this.isMonitoring) {
  27272. if (window.requestAnimationFrame) {
  27273. window.requestAnimationFrame(function () {
  27274. _this._checkGamepadsStatus();
  27275. });
  27276. }
  27277. else if (window.mozRequestAnimationFrame) {
  27278. window.mozRequestAnimationFrame(function () {
  27279. _this._checkGamepadsStatus();
  27280. });
  27281. }
  27282. else if (window.webkitRequestAnimationFrame) {
  27283. window.webkitRequestAnimationFrame(function () {
  27284. _this._checkGamepadsStatus();
  27285. });
  27286. }
  27287. }
  27288. };
  27289. // This function is called only on Chrome, which does not yet support
  27290. // connection/disconnection events, but requires you to monitor
  27291. // an array for changes.
  27292. Gamepads.prototype._updateGamepadObjects = function () {
  27293. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  27294. for (var i = 0; i < gamepads.length; i++) {
  27295. if (gamepads[i]) {
  27296. if (!(gamepads[i].index in this.babylonGamepads)) {
  27297. var newGamepad = this._addNewGamepad(gamepads[i]);
  27298. if (this._callbackGamepadConnected) {
  27299. this._callbackGamepadConnected(newGamepad);
  27300. }
  27301. }
  27302. else {
  27303. this.babylonGamepads[i].browserGamepad = gamepads[i];
  27304. }
  27305. }
  27306. }
  27307. };
  27308. return Gamepads;
  27309. })();
  27310. BABYLON.Gamepads = Gamepads;
  27311. var StickValues = (function () {
  27312. function StickValues(x, y) {
  27313. this.x = x;
  27314. this.y = y;
  27315. }
  27316. return StickValues;
  27317. })();
  27318. BABYLON.StickValues = StickValues;
  27319. var Gamepad = (function () {
  27320. function Gamepad(id, index, browserGamepad) {
  27321. this.id = id;
  27322. this.index = index;
  27323. this.browserGamepad = browserGamepad;
  27324. if (this.browserGamepad.axes.length >= 2) {
  27325. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  27326. }
  27327. if (this.browserGamepad.axes.length >= 4) {
  27328. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  27329. }
  27330. }
  27331. Gamepad.prototype.onleftstickchanged = function (callback) {
  27332. this._onleftstickchanged = callback;
  27333. };
  27334. Gamepad.prototype.onrightstickchanged = function (callback) {
  27335. this._onrightstickchanged = callback;
  27336. };
  27337. Object.defineProperty(Gamepad.prototype, "leftStick", {
  27338. get: function () {
  27339. return this._leftStick;
  27340. },
  27341. set: function (newValues) {
  27342. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  27343. this._onleftstickchanged(newValues);
  27344. }
  27345. this._leftStick = newValues;
  27346. },
  27347. enumerable: true,
  27348. configurable: true
  27349. });
  27350. Object.defineProperty(Gamepad.prototype, "rightStick", {
  27351. get: function () {
  27352. return this._rightStick;
  27353. },
  27354. set: function (newValues) {
  27355. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  27356. this._onrightstickchanged(newValues);
  27357. }
  27358. this._rightStick = newValues;
  27359. },
  27360. enumerable: true,
  27361. configurable: true
  27362. });
  27363. Gamepad.prototype.update = function () {
  27364. if (this._leftStick) {
  27365. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  27366. }
  27367. if (this._rightStick) {
  27368. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  27369. }
  27370. };
  27371. return Gamepad;
  27372. })();
  27373. BABYLON.Gamepad = Gamepad;
  27374. var GenericPad = (function (_super) {
  27375. __extends(GenericPad, _super);
  27376. function GenericPad(id, index, gamepad) {
  27377. _super.call(this, id, index, gamepad);
  27378. this.id = id;
  27379. this.index = index;
  27380. this.gamepad = gamepad;
  27381. this._buttons = new Array(gamepad.buttons.length);
  27382. }
  27383. GenericPad.prototype.onbuttondown = function (callback) {
  27384. this._onbuttondown = callback;
  27385. };
  27386. GenericPad.prototype.onbuttonup = function (callback) {
  27387. this._onbuttonup = callback;
  27388. };
  27389. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  27390. if (newValue !== currentValue) {
  27391. if (this._onbuttondown && newValue === 1) {
  27392. this._onbuttondown(buttonIndex);
  27393. }
  27394. if (this._onbuttonup && newValue === 0) {
  27395. this._onbuttonup(buttonIndex);
  27396. }
  27397. }
  27398. return newValue;
  27399. };
  27400. GenericPad.prototype.update = function () {
  27401. _super.prototype.update.call(this);
  27402. for (var index = 0; index < this._buttons.length; index++) {
  27403. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  27404. }
  27405. };
  27406. return GenericPad;
  27407. })(Gamepad);
  27408. BABYLON.GenericPad = GenericPad;
  27409. (function (Xbox360Button) {
  27410. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  27411. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  27412. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  27413. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  27414. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  27415. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  27416. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  27417. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  27418. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  27419. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  27420. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  27421. var Xbox360Button = BABYLON.Xbox360Button;
  27422. (function (Xbox360Dpad) {
  27423. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  27424. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  27425. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  27426. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  27427. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  27428. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  27429. var Xbox360Pad = (function (_super) {
  27430. __extends(Xbox360Pad, _super);
  27431. function Xbox360Pad() {
  27432. _super.apply(this, arguments);
  27433. this._leftTrigger = 0;
  27434. this._rightTrigger = 0;
  27435. this._buttonA = 0;
  27436. this._buttonB = 0;
  27437. this._buttonX = 0;
  27438. this._buttonY = 0;
  27439. this._buttonBack = 0;
  27440. this._buttonStart = 0;
  27441. this._buttonLB = 0;
  27442. this._buttonRB = 0;
  27443. this._buttonLeftStick = 0;
  27444. this._buttonRightStick = 0;
  27445. this._dPadUp = 0;
  27446. this._dPadDown = 0;
  27447. this._dPadLeft = 0;
  27448. this._dPadRight = 0;
  27449. }
  27450. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  27451. this._onlefttriggerchanged = callback;
  27452. };
  27453. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  27454. this._onrighttriggerchanged = callback;
  27455. };
  27456. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  27457. get: function () {
  27458. return this._leftTrigger;
  27459. },
  27460. set: function (newValue) {
  27461. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  27462. this._onlefttriggerchanged(newValue);
  27463. }
  27464. this._leftTrigger = newValue;
  27465. },
  27466. enumerable: true,
  27467. configurable: true
  27468. });
  27469. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  27470. get: function () {
  27471. return this._rightTrigger;
  27472. },
  27473. set: function (newValue) {
  27474. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  27475. this._onrighttriggerchanged(newValue);
  27476. }
  27477. this._rightTrigger = newValue;
  27478. },
  27479. enumerable: true,
  27480. configurable: true
  27481. });
  27482. Xbox360Pad.prototype.onbuttondown = function (callback) {
  27483. this._onbuttondown = callback;
  27484. };
  27485. Xbox360Pad.prototype.onbuttonup = function (callback) {
  27486. this._onbuttonup = callback;
  27487. };
  27488. Xbox360Pad.prototype.ondpaddown = function (callback) {
  27489. this._ondpaddown = callback;
  27490. };
  27491. Xbox360Pad.prototype.ondpadup = function (callback) {
  27492. this._ondpadup = callback;
  27493. };
  27494. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  27495. if (newValue !== currentValue) {
  27496. if (this._onbuttondown && newValue === 1) {
  27497. this._onbuttondown(buttonType);
  27498. }
  27499. if (this._onbuttonup && newValue === 0) {
  27500. this._onbuttonup(buttonType);
  27501. }
  27502. }
  27503. return newValue;
  27504. };
  27505. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  27506. if (newValue !== currentValue) {
  27507. if (this._ondpaddown && newValue === 1) {
  27508. this._ondpaddown(buttonType);
  27509. }
  27510. if (this._ondpadup && newValue === 0) {
  27511. this._ondpadup(buttonType);
  27512. }
  27513. }
  27514. return newValue;
  27515. };
  27516. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  27517. get: function () {
  27518. return this._buttonA;
  27519. },
  27520. set: function (value) {
  27521. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  27522. },
  27523. enumerable: true,
  27524. configurable: true
  27525. });
  27526. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  27527. get: function () {
  27528. return this._buttonB;
  27529. },
  27530. set: function (value) {
  27531. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  27532. },
  27533. enumerable: true,
  27534. configurable: true
  27535. });
  27536. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  27537. get: function () {
  27538. return this._buttonX;
  27539. },
  27540. set: function (value) {
  27541. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  27542. },
  27543. enumerable: true,
  27544. configurable: true
  27545. });
  27546. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  27547. get: function () {
  27548. return this._buttonY;
  27549. },
  27550. set: function (value) {
  27551. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  27552. },
  27553. enumerable: true,
  27554. configurable: true
  27555. });
  27556. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  27557. get: function () {
  27558. return this._buttonStart;
  27559. },
  27560. set: function (value) {
  27561. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  27562. },
  27563. enumerable: true,
  27564. configurable: true
  27565. });
  27566. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  27567. get: function () {
  27568. return this._buttonBack;
  27569. },
  27570. set: function (value) {
  27571. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  27572. },
  27573. enumerable: true,
  27574. configurable: true
  27575. });
  27576. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  27577. get: function () {
  27578. return this._buttonLB;
  27579. },
  27580. set: function (value) {
  27581. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  27582. },
  27583. enumerable: true,
  27584. configurable: true
  27585. });
  27586. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  27587. get: function () {
  27588. return this._buttonRB;
  27589. },
  27590. set: function (value) {
  27591. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  27592. },
  27593. enumerable: true,
  27594. configurable: true
  27595. });
  27596. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  27597. get: function () {
  27598. return this._buttonLeftStick;
  27599. },
  27600. set: function (value) {
  27601. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  27602. },
  27603. enumerable: true,
  27604. configurable: true
  27605. });
  27606. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  27607. get: function () {
  27608. return this._buttonRightStick;
  27609. },
  27610. set: function (value) {
  27611. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  27612. },
  27613. enumerable: true,
  27614. configurable: true
  27615. });
  27616. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  27617. get: function () {
  27618. return this._dPadUp;
  27619. },
  27620. set: function (value) {
  27621. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  27622. },
  27623. enumerable: true,
  27624. configurable: true
  27625. });
  27626. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  27627. get: function () {
  27628. return this._dPadDown;
  27629. },
  27630. set: function (value) {
  27631. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  27632. },
  27633. enumerable: true,
  27634. configurable: true
  27635. });
  27636. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  27637. get: function () {
  27638. return this._dPadLeft;
  27639. },
  27640. set: function (value) {
  27641. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  27642. },
  27643. enumerable: true,
  27644. configurable: true
  27645. });
  27646. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  27647. get: function () {
  27648. return this._dPadRight;
  27649. },
  27650. set: function (value) {
  27651. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  27652. },
  27653. enumerable: true,
  27654. configurable: true
  27655. });
  27656. Xbox360Pad.prototype.update = function () {
  27657. _super.prototype.update.call(this);
  27658. this.buttonA = this.browserGamepad.buttons[0].value;
  27659. this.buttonB = this.browserGamepad.buttons[1].value;
  27660. this.buttonX = this.browserGamepad.buttons[2].value;
  27661. this.buttonY = this.browserGamepad.buttons[3].value;
  27662. this.buttonLB = this.browserGamepad.buttons[4].value;
  27663. this.buttonRB = this.browserGamepad.buttons[5].value;
  27664. this.leftTrigger = this.browserGamepad.buttons[6].value;
  27665. this.rightTrigger = this.browserGamepad.buttons[7].value;
  27666. this.buttonBack = this.browserGamepad.buttons[8].value;
  27667. this.buttonStart = this.browserGamepad.buttons[9].value;
  27668. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  27669. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  27670. this.dPadUp = this.browserGamepad.buttons[12].value;
  27671. this.dPadDown = this.browserGamepad.buttons[13].value;
  27672. this.dPadLeft = this.browserGamepad.buttons[14].value;
  27673. this.dPadRight = this.browserGamepad.buttons[15].value;
  27674. };
  27675. return Xbox360Pad;
  27676. })(Gamepad);
  27677. BABYLON.Xbox360Pad = Xbox360Pad;
  27678. })(BABYLON || (BABYLON = {}));
  27679. //# sourceMappingURL=babylon.gamepads.js.map
  27680. var __extends = this.__extends || function (d, b) {
  27681. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27682. function __() { this.constructor = d; }
  27683. __.prototype = b.prototype;
  27684. d.prototype = new __();
  27685. };
  27686. var BABYLON;
  27687. (function (BABYLON) {
  27688. // We're mainly based on the logic defined into the FreeCamera code
  27689. var GamepadCamera = (function (_super) {
  27690. __extends(GamepadCamera, _super);
  27691. function GamepadCamera(name, position, scene) {
  27692. var _this = this;
  27693. _super.call(this, name, position, scene);
  27694. this.angularSensibility = 200;
  27695. this.moveSensibility = 75;
  27696. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  27697. _this._onNewGameConnected(gamepad);
  27698. });
  27699. }
  27700. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  27701. // Only the first gamepad can control the camera
  27702. if (gamepad.index === 0) {
  27703. this._gamepad = gamepad;
  27704. }
  27705. };
  27706. GamepadCamera.prototype._checkInputs = function () {
  27707. if (this._gamepad) {
  27708. var LSValues = this._gamepad.leftStick;
  27709. var normalizedLX = LSValues.x / this.moveSensibility;
  27710. var normalizedLY = LSValues.y / this.moveSensibility;
  27711. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  27712. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  27713. var RSValues = this._gamepad.rightStick;
  27714. var normalizedRX = RSValues.x / this.angularSensibility;
  27715. var normalizedRY = RSValues.y / this.angularSensibility;
  27716. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  27717. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  27718. ;
  27719. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  27720. var speed = this._computeLocalCameraSpeed() * 50.0;
  27721. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  27722. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  27723. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  27724. }
  27725. _super.prototype._checkInputs.call(this);
  27726. };
  27727. GamepadCamera.prototype.dispose = function () {
  27728. this._gamepads.dispose();
  27729. _super.prototype.dispose.call(this);
  27730. };
  27731. return GamepadCamera;
  27732. })(BABYLON.FreeCamera);
  27733. BABYLON.GamepadCamera = GamepadCamera;
  27734. })(BABYLON || (BABYLON = {}));
  27735. //# sourceMappingURL=babylon.gamepadCamera.js.map
  27736. var __extends = this.__extends || function (d, b) {
  27737. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  27738. function __() { this.constructor = d; }
  27739. __.prototype = b.prototype;
  27740. d.prototype = new __();
  27741. };
  27742. var BABYLON;
  27743. (function (BABYLON) {
  27744. var LinesMesh = (function (_super) {
  27745. __extends(LinesMesh, _super);
  27746. function LinesMesh(name, scene, updatable) {
  27747. if (updatable === void 0) { updatable = false; }
  27748. _super.call(this, name, scene);
  27749. this.color = new BABYLON.Color3(1, 1, 1);
  27750. this.alpha = 1;
  27751. this._indices = new Array();
  27752. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27753. attributes: ["position"],
  27754. uniforms: ["worldViewProjection", "color"],
  27755. needAlphaBlending: true
  27756. });
  27757. }
  27758. Object.defineProperty(LinesMesh.prototype, "material", {
  27759. get: function () {
  27760. return this._colorShader;
  27761. },
  27762. enumerable: true,
  27763. configurable: true
  27764. });
  27765. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27766. get: function () {
  27767. return false;
  27768. },
  27769. enumerable: true,
  27770. configurable: true
  27771. });
  27772. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27773. get: function () {
  27774. return false;
  27775. },
  27776. enumerable: true,
  27777. configurable: true
  27778. });
  27779. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27780. var engine = this.getScene().getEngine();
  27781. var indexToBind = this._geometry.getIndexBuffer();
  27782. // VBOs
  27783. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27784. // Color
  27785. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27786. };
  27787. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27788. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27789. return;
  27790. }
  27791. var engine = this.getScene().getEngine();
  27792. // Draw order
  27793. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27794. };
  27795. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27796. return null;
  27797. };
  27798. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27799. this._colorShader.dispose();
  27800. _super.prototype.dispose.call(this, doNotRecurse);
  27801. };
  27802. return LinesMesh;
  27803. })(BABYLON.Mesh);
  27804. BABYLON.LinesMesh = LinesMesh;
  27805. })(BABYLON || (BABYLON = {}));
  27806. //# sourceMappingURL=babylon.linesMesh.js.map
  27807. var BABYLON;
  27808. (function (BABYLON) {
  27809. var OutlineRenderer = (function () {
  27810. function OutlineRenderer(scene) {
  27811. this._scene = scene;
  27812. }
  27813. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  27814. var _this = this;
  27815. if (useOverlay === void 0) { useOverlay = false; }
  27816. var scene = this._scene;
  27817. var engine = this._scene.getEngine();
  27818. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27819. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  27820. return;
  27821. }
  27822. var mesh = subMesh.getRenderingMesh();
  27823. var material = subMesh.getMaterial();
  27824. engine.enableEffect(this._effect);
  27825. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  27826. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  27827. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27828. // Bones
  27829. if (mesh.useBones) {
  27830. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27831. }
  27832. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  27833. // Alpha test
  27834. if (material && material.needAlphaTesting()) {
  27835. var alphaTexture = material.getAlphaTestTexture();
  27836. this._effect.setTexture("diffuseSampler", alphaTexture);
  27837. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27838. }
  27839. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  27840. _this._effect.setMatrix("world", world);
  27841. });
  27842. };
  27843. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  27844. var defines = [];
  27845. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  27846. var mesh = subMesh.getMesh();
  27847. var material = subMesh.getMaterial();
  27848. // Alpha test
  27849. if (material && material.needAlphaTesting()) {
  27850. defines.push("#define ALPHATEST");
  27851. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27852. attribs.push(BABYLON.VertexBuffer.UVKind);
  27853. defines.push("#define UV1");
  27854. }
  27855. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27856. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27857. defines.push("#define UV2");
  27858. }
  27859. }
  27860. // Bones
  27861. if (mesh.useBones) {
  27862. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27863. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27864. defines.push("#define BONES");
  27865. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27866. }
  27867. // Instances
  27868. if (useInstances) {
  27869. defines.push("#define INSTANCES");
  27870. attribs.push("world0");
  27871. attribs.push("world1");
  27872. attribs.push("world2");
  27873. attribs.push("world3");
  27874. }
  27875. // Get correct effect
  27876. var join = defines.join("\n");
  27877. if (this._cachedDefines !== join) {
  27878. this._cachedDefines = join;
  27879. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  27880. }
  27881. return this._effect.isReady();
  27882. };
  27883. return OutlineRenderer;
  27884. })();
  27885. BABYLON.OutlineRenderer = OutlineRenderer;
  27886. })(BABYLON || (BABYLON = {}));
  27887. //# sourceMappingURL=babylon.outlineRenderer.js.map
  27888. var BABYLON;
  27889. (function (BABYLON) {
  27890. var MeshAssetTask = (function () {
  27891. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  27892. this.name = name;
  27893. this.meshesNames = meshesNames;
  27894. this.rootUrl = rootUrl;
  27895. this.sceneFilename = sceneFilename;
  27896. this.isCompleted = false;
  27897. }
  27898. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27899. var _this = this;
  27900. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  27901. _this.loadedMeshes = meshes;
  27902. _this.loadedParticleSystems = particleSystems;
  27903. _this.loadedSkeletons = skeletons;
  27904. _this.isCompleted = true;
  27905. if (_this.onSuccess) {
  27906. _this.onSuccess(_this);
  27907. }
  27908. onSuccess();
  27909. }, null, function () {
  27910. if (_this.onError) {
  27911. _this.onError(_this);
  27912. }
  27913. onError();
  27914. });
  27915. };
  27916. return MeshAssetTask;
  27917. })();
  27918. BABYLON.MeshAssetTask = MeshAssetTask;
  27919. var TextFileAssetTask = (function () {
  27920. function TextFileAssetTask(name, url) {
  27921. this.name = name;
  27922. this.url = url;
  27923. this.isCompleted = false;
  27924. }
  27925. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27926. var _this = this;
  27927. BABYLON.Tools.LoadFile(this.url, function (data) {
  27928. _this.text = data;
  27929. _this.isCompleted = true;
  27930. if (_this.onSuccess) {
  27931. _this.onSuccess(_this);
  27932. }
  27933. onSuccess();
  27934. }, null, scene.database, false, function () {
  27935. if (_this.onError) {
  27936. _this.onError(_this);
  27937. }
  27938. onError();
  27939. });
  27940. };
  27941. return TextFileAssetTask;
  27942. })();
  27943. BABYLON.TextFileAssetTask = TextFileAssetTask;
  27944. var BinaryFileAssetTask = (function () {
  27945. function BinaryFileAssetTask(name, url) {
  27946. this.name = name;
  27947. this.url = url;
  27948. this.isCompleted = false;
  27949. }
  27950. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27951. var _this = this;
  27952. BABYLON.Tools.LoadFile(this.url, function (data) {
  27953. _this.data = data;
  27954. _this.isCompleted = true;
  27955. if (_this.onSuccess) {
  27956. _this.onSuccess(_this);
  27957. }
  27958. onSuccess();
  27959. }, null, scene.database, true, function () {
  27960. if (_this.onError) {
  27961. _this.onError(_this);
  27962. }
  27963. onError();
  27964. });
  27965. };
  27966. return BinaryFileAssetTask;
  27967. })();
  27968. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  27969. var ImageAssetTask = (function () {
  27970. function ImageAssetTask(name, url) {
  27971. this.name = name;
  27972. this.url = url;
  27973. this.isCompleted = false;
  27974. }
  27975. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  27976. var _this = this;
  27977. var img = new Image();
  27978. img.onload = function () {
  27979. _this.image = img;
  27980. _this.isCompleted = true;
  27981. if (_this.onSuccess) {
  27982. _this.onSuccess(_this);
  27983. }
  27984. onSuccess();
  27985. };
  27986. img.onerror = function () {
  27987. if (_this.onError) {
  27988. _this.onError(_this);
  27989. }
  27990. onError();
  27991. };
  27992. img.src = this.url;
  27993. };
  27994. return ImageAssetTask;
  27995. })();
  27996. BABYLON.ImageAssetTask = ImageAssetTask;
  27997. var TextureAssetTask = (function () {
  27998. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  27999. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28000. this.name = name;
  28001. this.url = url;
  28002. this.noMipmap = noMipmap;
  28003. this.invertY = invertY;
  28004. this.samplingMode = samplingMode;
  28005. this.isCompleted = false;
  28006. }
  28007. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28008. var _this = this;
  28009. var onload = function () {
  28010. _this.isCompleted = true;
  28011. if (_this.onSuccess) {
  28012. _this.onSuccess(_this);
  28013. }
  28014. onSuccess();
  28015. };
  28016. var onerror = function () {
  28017. if (_this.onError) {
  28018. _this.onError(_this);
  28019. }
  28020. onError();
  28021. };
  28022. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  28023. };
  28024. return TextureAssetTask;
  28025. })();
  28026. BABYLON.TextureAssetTask = TextureAssetTask;
  28027. var AssetsManager = (function () {
  28028. function AssetsManager(scene) {
  28029. this._tasks = new Array();
  28030. this._waitingTasksCount = 0;
  28031. this.useDefaultLoadingScreen = true;
  28032. this._scene = scene;
  28033. }
  28034. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  28035. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  28036. this._tasks.push(task);
  28037. return task;
  28038. };
  28039. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  28040. var task = new TextFileAssetTask(taskName, url);
  28041. this._tasks.push(task);
  28042. return task;
  28043. };
  28044. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  28045. var task = new BinaryFileAssetTask(taskName, url);
  28046. this._tasks.push(task);
  28047. return task;
  28048. };
  28049. AssetsManager.prototype.addImageTask = function (taskName, url) {
  28050. var task = new ImageAssetTask(taskName, url);
  28051. this._tasks.push(task);
  28052. return task;
  28053. };
  28054. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  28055. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28056. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  28057. this._tasks.push(task);
  28058. return task;
  28059. };
  28060. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  28061. this._waitingTasksCount--;
  28062. if (this._waitingTasksCount === 0) {
  28063. if (this.onFinish) {
  28064. this.onFinish(this._tasks);
  28065. }
  28066. this._scene.getEngine().hideLoadingUI();
  28067. }
  28068. };
  28069. AssetsManager.prototype._runTask = function (task) {
  28070. var _this = this;
  28071. task.run(this._scene, function () {
  28072. if (_this.onTaskSuccess) {
  28073. _this.onTaskSuccess(task);
  28074. }
  28075. _this._decreaseWaitingTasksCount();
  28076. }, function () {
  28077. if (_this.onTaskError) {
  28078. _this.onTaskError(task);
  28079. }
  28080. _this._decreaseWaitingTasksCount();
  28081. });
  28082. };
  28083. AssetsManager.prototype.reset = function () {
  28084. this._tasks = new Array();
  28085. return this;
  28086. };
  28087. AssetsManager.prototype.load = function () {
  28088. this._waitingTasksCount = this._tasks.length;
  28089. if (this._waitingTasksCount === 0) {
  28090. if (this.onFinish) {
  28091. this.onFinish(this._tasks);
  28092. }
  28093. return this;
  28094. }
  28095. if (this.useDefaultLoadingScreen) {
  28096. this._scene.getEngine().displayLoadingUI();
  28097. }
  28098. for (var index = 0; index < this._tasks.length; index++) {
  28099. var task = this._tasks[index];
  28100. this._runTask(task);
  28101. }
  28102. return this;
  28103. };
  28104. return AssetsManager;
  28105. })();
  28106. BABYLON.AssetsManager = AssetsManager;
  28107. })(BABYLON || (BABYLON = {}));
  28108. //# sourceMappingURL=babylon.assetsManager.js.map
  28109. var __extends = this.__extends || function (d, b) {
  28110. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28111. function __() { this.constructor = d; }
  28112. __.prototype = b.prototype;
  28113. d.prototype = new __();
  28114. };
  28115. var BABYLON;
  28116. (function (BABYLON) {
  28117. var VRDeviceOrientationFreeCamera = (function (_super) {
  28118. __extends(VRDeviceOrientationFreeCamera, _super);
  28119. function VRDeviceOrientationFreeCamera(name, position, scene) {
  28120. _super.call(this, name, position, scene);
  28121. this._alpha = 0;
  28122. this._beta = 0;
  28123. this._gamma = 0;
  28124. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR);
  28125. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  28126. }
  28127. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  28128. this._alpha = +evt.alpha | 0;
  28129. this._beta = +evt.beta | 0;
  28130. this._gamma = +evt.gamma | 0;
  28131. if (this._gamma < 0) {
  28132. this._gamma = 90 + this._gamma;
  28133. }
  28134. else {
  28135. // Incline it in the correct angle.
  28136. this._gamma = 270 - this._gamma;
  28137. }
  28138. this.rotation.x = this._gamma / 180.0 * Math.PI;
  28139. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28140. this.rotation.z = this._beta / 180.0 * Math.PI;
  28141. };
  28142. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28143. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28144. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  28145. };
  28146. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  28147. _super.prototype.detachControl.call(this, element);
  28148. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  28149. };
  28150. return VRDeviceOrientationFreeCamera;
  28151. })(BABYLON.FreeCamera);
  28152. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  28153. })(BABYLON || (BABYLON = {}));
  28154. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28155. var __extends = this.__extends || function (d, b) {
  28156. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28157. function __() { this.constructor = d; }
  28158. __.prototype = b.prototype;
  28159. d.prototype = new __();
  28160. };
  28161. var BABYLON;
  28162. (function (BABYLON) {
  28163. var WebVRFreeCamera = (function (_super) {
  28164. __extends(WebVRFreeCamera, _super);
  28165. function WebVRFreeCamera(name, position, scene) {
  28166. _super.call(this, name, position, scene);
  28167. this._hmdDevice = null;
  28168. this._sensorDevice = null;
  28169. this._cacheState = null;
  28170. this._cacheQuaternion = new BABYLON.Quaternion();
  28171. this._cacheRotation = BABYLON.Vector3.Zero();
  28172. this._vrEnabled = false;
  28173. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR);
  28174. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28175. }
  28176. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  28177. var size = devices.length;
  28178. var i = 0;
  28179. // Reset devices.
  28180. this._sensorDevice = null;
  28181. this._hmdDevice = null;
  28182. while (i < size && this._hmdDevice === null) {
  28183. if (devices[i] instanceof HMDVRDevice) {
  28184. this._hmdDevice = devices[i];
  28185. }
  28186. i++;
  28187. }
  28188. i = 0;
  28189. while (i < size && this._sensorDevice === null) {
  28190. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28191. this._sensorDevice = devices[i];
  28192. }
  28193. i++;
  28194. }
  28195. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28196. };
  28197. WebVRFreeCamera.prototype._checkInputs = function () {
  28198. if (this._vrEnabled) {
  28199. this._cacheState = this._sensorDevice.getState();
  28200. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28201. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28202. this.rotation.x = -this._cacheRotation.z;
  28203. this.rotation.y = -this._cacheRotation.y;
  28204. this.rotation.z = this._cacheRotation.x;
  28205. }
  28206. _super.prototype._checkInputs.call(this);
  28207. };
  28208. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28209. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28210. if (navigator.getVRDevices) {
  28211. navigator.getVRDevices().then(this._getWebVRDevices);
  28212. }
  28213. else if (navigator.mozGetVRDevices) {
  28214. navigator.mozGetVRDevices(this._getWebVRDevices);
  28215. }
  28216. };
  28217. WebVRFreeCamera.prototype.detachControl = function (element) {
  28218. _super.prototype.detachControl.call(this, element);
  28219. this._vrEnabled = false;
  28220. };
  28221. return WebVRFreeCamera;
  28222. })(BABYLON.FreeCamera);
  28223. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  28224. })(BABYLON || (BABYLON = {}));
  28225. //# sourceMappingURL=babylon.webVRCamera.js.map
  28226. var __extends = this.__extends || function (d, b) {
  28227. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  28228. function __() { this.constructor = d; }
  28229. __.prototype = b.prototype;
  28230. d.prototype = new __();
  28231. };
  28232. var BABYLON;
  28233. (function (BABYLON) {
  28234. // Standard optimizations
  28235. var SceneOptimization = (function () {
  28236. function SceneOptimization(priority) {
  28237. if (priority === void 0) { priority = 0; }
  28238. this.priority = priority;
  28239. this.apply = function (scene) {
  28240. return true; // Return true if everything that can be done was applied
  28241. };
  28242. }
  28243. return SceneOptimization;
  28244. })();
  28245. BABYLON.SceneOptimization = SceneOptimization;
  28246. var TextureOptimization = (function (_super) {
  28247. __extends(TextureOptimization, _super);
  28248. function TextureOptimization(priority, maximumSize) {
  28249. var _this = this;
  28250. if (priority === void 0) { priority = 0; }
  28251. if (maximumSize === void 0) { maximumSize = 1024; }
  28252. _super.call(this, priority);
  28253. this.priority = priority;
  28254. this.maximumSize = maximumSize;
  28255. this.apply = function (scene) {
  28256. var allDone = true;
  28257. for (var index = 0; index < scene.textures.length; index++) {
  28258. var texture = scene.textures[index];
  28259. if (!texture.canRescale) {
  28260. continue;
  28261. }
  28262. var currentSize = texture.getSize();
  28263. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28264. if (maxDimension > _this.maximumSize) {
  28265. texture.scale(0.5);
  28266. allDone = false;
  28267. }
  28268. }
  28269. return allDone;
  28270. };
  28271. }
  28272. return TextureOptimization;
  28273. })(SceneOptimization);
  28274. BABYLON.TextureOptimization = TextureOptimization;
  28275. var HardwareScalingOptimization = (function (_super) {
  28276. __extends(HardwareScalingOptimization, _super);
  28277. function HardwareScalingOptimization(priority, maximumScale) {
  28278. var _this = this;
  28279. if (priority === void 0) { priority = 0; }
  28280. if (maximumScale === void 0) { maximumScale = 2; }
  28281. _super.call(this, priority);
  28282. this.priority = priority;
  28283. this.maximumScale = maximumScale;
  28284. this._currentScale = 1;
  28285. this.apply = function (scene) {
  28286. _this._currentScale++;
  28287. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28288. return _this._currentScale >= _this.maximumScale;
  28289. };
  28290. }
  28291. return HardwareScalingOptimization;
  28292. })(SceneOptimization);
  28293. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28294. var ShadowsOptimization = (function (_super) {
  28295. __extends(ShadowsOptimization, _super);
  28296. function ShadowsOptimization() {
  28297. _super.apply(this, arguments);
  28298. this.apply = function (scene) {
  28299. scene.shadowsEnabled = false;
  28300. return true;
  28301. };
  28302. }
  28303. return ShadowsOptimization;
  28304. })(SceneOptimization);
  28305. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28306. var PostProcessesOptimization = (function (_super) {
  28307. __extends(PostProcessesOptimization, _super);
  28308. function PostProcessesOptimization() {
  28309. _super.apply(this, arguments);
  28310. this.apply = function (scene) {
  28311. scene.postProcessesEnabled = false;
  28312. return true;
  28313. };
  28314. }
  28315. return PostProcessesOptimization;
  28316. })(SceneOptimization);
  28317. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28318. var LensFlaresOptimization = (function (_super) {
  28319. __extends(LensFlaresOptimization, _super);
  28320. function LensFlaresOptimization() {
  28321. _super.apply(this, arguments);
  28322. this.apply = function (scene) {
  28323. scene.lensFlaresEnabled = false;
  28324. return true;
  28325. };
  28326. }
  28327. return LensFlaresOptimization;
  28328. })(SceneOptimization);
  28329. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28330. var ParticlesOptimization = (function (_super) {
  28331. __extends(ParticlesOptimization, _super);
  28332. function ParticlesOptimization() {
  28333. _super.apply(this, arguments);
  28334. this.apply = function (scene) {
  28335. scene.particlesEnabled = false;
  28336. return true;
  28337. };
  28338. }
  28339. return ParticlesOptimization;
  28340. })(SceneOptimization);
  28341. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28342. var RenderTargetsOptimization = (function (_super) {
  28343. __extends(RenderTargetsOptimization, _super);
  28344. function RenderTargetsOptimization() {
  28345. _super.apply(this, arguments);
  28346. this.apply = function (scene) {
  28347. scene.renderTargetsEnabled = false;
  28348. return true;
  28349. };
  28350. }
  28351. return RenderTargetsOptimization;
  28352. })(SceneOptimization);
  28353. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28354. var MergeMeshesOptimization = (function (_super) {
  28355. __extends(MergeMeshesOptimization, _super);
  28356. function MergeMeshesOptimization() {
  28357. var _this = this;
  28358. _super.apply(this, arguments);
  28359. this._canBeMerged = function (abstractMesh) {
  28360. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28361. return false;
  28362. }
  28363. var mesh = abstractMesh;
  28364. if (!mesh.isVisible || !mesh.isEnabled()) {
  28365. return false;
  28366. }
  28367. if (mesh.instances.length > 0) {
  28368. return false;
  28369. }
  28370. if (mesh.skeleton || mesh.hasLODLevels) {
  28371. return false;
  28372. }
  28373. return true;
  28374. };
  28375. this.apply = function (scene) {
  28376. var globalPool = scene.meshes.slice(0);
  28377. var globalLength = globalPool.length;
  28378. for (var index = 0; index < globalLength; index++) {
  28379. var currentPool = new Array();
  28380. var current = globalPool[index];
  28381. // Checks
  28382. if (!_this._canBeMerged(current)) {
  28383. continue;
  28384. }
  28385. currentPool.push(current);
  28386. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28387. var otherMesh = globalPool[subIndex];
  28388. if (!_this._canBeMerged(otherMesh)) {
  28389. continue;
  28390. }
  28391. if (otherMesh.material !== current.material) {
  28392. continue;
  28393. }
  28394. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28395. continue;
  28396. }
  28397. currentPool.push(otherMesh);
  28398. globalLength--;
  28399. globalPool.splice(subIndex, 1);
  28400. subIndex--;
  28401. }
  28402. if (currentPool.length < 2) {
  28403. continue;
  28404. }
  28405. // Merge meshes
  28406. BABYLON.Mesh.MergeMeshes(currentPool);
  28407. }
  28408. return true;
  28409. };
  28410. }
  28411. return MergeMeshesOptimization;
  28412. })(SceneOptimization);
  28413. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28414. // Options
  28415. var SceneOptimizerOptions = (function () {
  28416. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28417. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28418. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28419. this.targetFrameRate = targetFrameRate;
  28420. this.trackerDuration = trackerDuration;
  28421. this.optimizations = new Array();
  28422. }
  28423. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28424. var result = new SceneOptimizerOptions(targetFrameRate);
  28425. var priority = 0;
  28426. result.optimizations.push(new MergeMeshesOptimization(priority));
  28427. result.optimizations.push(new ShadowsOptimization(priority));
  28428. result.optimizations.push(new LensFlaresOptimization(priority));
  28429. // Next priority
  28430. priority++;
  28431. result.optimizations.push(new PostProcessesOptimization(priority));
  28432. result.optimizations.push(new ParticlesOptimization(priority));
  28433. // Next priority
  28434. priority++;
  28435. result.optimizations.push(new TextureOptimization(priority, 1024));
  28436. return result;
  28437. };
  28438. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28439. var result = new SceneOptimizerOptions(targetFrameRate);
  28440. var priority = 0;
  28441. result.optimizations.push(new MergeMeshesOptimization(priority));
  28442. result.optimizations.push(new ShadowsOptimization(priority));
  28443. result.optimizations.push(new LensFlaresOptimization(priority));
  28444. // Next priority
  28445. priority++;
  28446. result.optimizations.push(new PostProcessesOptimization(priority));
  28447. result.optimizations.push(new ParticlesOptimization(priority));
  28448. // Next priority
  28449. priority++;
  28450. result.optimizations.push(new TextureOptimization(priority, 512));
  28451. // Next priority
  28452. priority++;
  28453. result.optimizations.push(new RenderTargetsOptimization(priority));
  28454. // Next priority
  28455. priority++;
  28456. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28457. return result;
  28458. };
  28459. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28460. var result = new SceneOptimizerOptions(targetFrameRate);
  28461. var priority = 0;
  28462. result.optimizations.push(new MergeMeshesOptimization(priority));
  28463. result.optimizations.push(new ShadowsOptimization(priority));
  28464. result.optimizations.push(new LensFlaresOptimization(priority));
  28465. // Next priority
  28466. priority++;
  28467. result.optimizations.push(new PostProcessesOptimization(priority));
  28468. result.optimizations.push(new ParticlesOptimization(priority));
  28469. // Next priority
  28470. priority++;
  28471. result.optimizations.push(new TextureOptimization(priority, 256));
  28472. // Next priority
  28473. priority++;
  28474. result.optimizations.push(new RenderTargetsOptimization(priority));
  28475. // Next priority
  28476. priority++;
  28477. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28478. return result;
  28479. };
  28480. return SceneOptimizerOptions;
  28481. })();
  28482. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28483. // Scene optimizer tool
  28484. var SceneOptimizer = (function () {
  28485. function SceneOptimizer() {
  28486. }
  28487. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28488. // TODO: add an epsilon
  28489. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28490. if (onSuccess) {
  28491. onSuccess();
  28492. }
  28493. return;
  28494. }
  28495. // Apply current level of optimizations
  28496. var allDone = true;
  28497. var noOptimizationApplied = true;
  28498. for (var index = 0; index < options.optimizations.length; index++) {
  28499. var optimization = options.optimizations[index];
  28500. if (optimization.priority === currentPriorityLevel) {
  28501. noOptimizationApplied = false;
  28502. allDone = allDone && optimization.apply(scene);
  28503. }
  28504. }
  28505. // If no optimization was applied, this is a failure :(
  28506. if (noOptimizationApplied) {
  28507. if (onFailure) {
  28508. onFailure();
  28509. }
  28510. return;
  28511. }
  28512. // If all optimizations were done, move to next level
  28513. if (allDone) {
  28514. currentPriorityLevel++;
  28515. }
  28516. // Let's the system running for a specific amount of time before checking FPS
  28517. scene.executeWhenReady(function () {
  28518. setTimeout(function () {
  28519. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28520. }, options.trackerDuration);
  28521. });
  28522. };
  28523. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28524. if (!options) {
  28525. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28526. }
  28527. // Let's the system running for a specific amount of time before checking FPS
  28528. scene.executeWhenReady(function () {
  28529. setTimeout(function () {
  28530. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28531. }, options.trackerDuration);
  28532. });
  28533. };
  28534. return SceneOptimizer;
  28535. })();
  28536. BABYLON.SceneOptimizer = SceneOptimizer;
  28537. })(BABYLON || (BABYLON = {}));
  28538. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28539. var BABYLON;
  28540. (function (BABYLON) {
  28541. var Internals;
  28542. (function (Internals) {
  28543. var MeshLODLevel = (function () {
  28544. function MeshLODLevel(distance, mesh) {
  28545. this.distance = distance;
  28546. this.mesh = mesh;
  28547. }
  28548. return MeshLODLevel;
  28549. })();
  28550. Internals.MeshLODLevel = MeshLODLevel;
  28551. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28552. })(BABYLON || (BABYLON = {}));
  28553. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28554. var BABYLON;
  28555. (function (BABYLON) {
  28556. var AudioEngine = (function () {
  28557. function AudioEngine() {
  28558. this._audioContext = null;
  28559. this._audioContextInitialized = false;
  28560. this.canUseWebAudio = false;
  28561. this.WarnedWebAudioUnsupported = false;
  28562. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28563. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28564. this.canUseWebAudio = true;
  28565. }
  28566. }
  28567. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28568. get: function () {
  28569. if (!this._audioContextInitialized) {
  28570. this._initializeAudioContext();
  28571. }
  28572. return this._audioContext;
  28573. },
  28574. enumerable: true,
  28575. configurable: true
  28576. });
  28577. AudioEngine.prototype._initializeAudioContext = function () {
  28578. try {
  28579. if (this.canUseWebAudio) {
  28580. this._audioContext = new AudioContext();
  28581. // create a global volume gain node
  28582. this.masterGain = this._audioContext.createGain();
  28583. this.masterGain.gain.value = 1;
  28584. this.masterGain.connect(this._audioContext.destination);
  28585. this._audioContextInitialized = true;
  28586. }
  28587. }
  28588. catch (e) {
  28589. this.canUseWebAudio = false;
  28590. BABYLON.Tools.Error("Web Audio: " + e.message);
  28591. }
  28592. };
  28593. AudioEngine.prototype.dispose = function () {
  28594. if (this.canUseWebAudio && this._audioContextInitialized) {
  28595. if (this._connectedAnalyser) {
  28596. this._connectedAnalyser.stopDebugCanvas();
  28597. this._connectedAnalyser.dispose();
  28598. this.masterGain.disconnect();
  28599. this.masterGain.connect(this._audioContext.destination);
  28600. this._connectedAnalyser = null;
  28601. }
  28602. this.masterGain.gain.value = 1;
  28603. }
  28604. this.WarnedWebAudioUnsupported = false;
  28605. };
  28606. AudioEngine.prototype.getGlobalVolume = function () {
  28607. if (this.canUseWebAudio && this._audioContextInitialized) {
  28608. return this.masterGain.gain.value;
  28609. }
  28610. else {
  28611. return -1;
  28612. }
  28613. };
  28614. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28615. if (this.canUseWebAudio && this._audioContextInitialized) {
  28616. this.masterGain.gain.value = newVolume;
  28617. }
  28618. };
  28619. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28620. if (this._connectedAnalyser) {
  28621. this._connectedAnalyser.stopDebugCanvas();
  28622. }
  28623. if (this.canUseWebAudio && this._audioContextInitialized) {
  28624. this._connectedAnalyser = analyser;
  28625. this.masterGain.disconnect();
  28626. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28627. }
  28628. };
  28629. return AudioEngine;
  28630. })();
  28631. BABYLON.AudioEngine = AudioEngine;
  28632. })(BABYLON || (BABYLON = {}));
  28633. //# sourceMappingURL=babylon.audioEngine.js.map
  28634. var BABYLON;
  28635. (function (BABYLON) {
  28636. var Sound = (function () {
  28637. /**
  28638. * Create a sound and attach it to a scene
  28639. * @param name Name of your sound
  28640. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  28641. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  28642. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  28643. */
  28644. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  28645. var _this = this;
  28646. this.autoplay = false;
  28647. this.loop = false;
  28648. this.useCustomAttenuation = false;
  28649. this.spatialSound = false;
  28650. this.refDistance = 1;
  28651. this.rolloffFactor = 1;
  28652. this.maxDistance = 100;
  28653. this.distanceModel = "linear";
  28654. this._panningModel = "equalpower";
  28655. this._playbackRate = 1;
  28656. this._startTime = 0;
  28657. this._startOffset = 0;
  28658. this._position = BABYLON.Vector3.Zero();
  28659. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  28660. this._volume = 1;
  28661. this._isLoaded = false;
  28662. this._isReadyToPlay = false;
  28663. this.isPlaying = false;
  28664. this.isPaused = false;
  28665. this._isDirectional = false;
  28666. // Used if you'd like to create a directional sound.
  28667. // If not set, the sound will be omnidirectional
  28668. this._coneInnerAngle = 360;
  28669. this._coneOuterAngle = 360;
  28670. this._coneOuterGain = 0;
  28671. this.name = name;
  28672. this._scene = scene;
  28673. this._readyToPlayCallback = readyToPlayCallback;
  28674. // Default custom attenuation function is a linear attenuation
  28675. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  28676. if (currentDistance < maxDistance) {
  28677. return currentVolume * (1 - currentDistance / maxDistance);
  28678. }
  28679. else {
  28680. return 0;
  28681. }
  28682. };
  28683. if (options) {
  28684. this.autoplay = options.autoplay || false;
  28685. this.loop = options.loop || false;
  28686. // if volume === 0, we need another way to check this option
  28687. if (options.volume !== undefined) {
  28688. this._volume = options.volume;
  28689. }
  28690. this.spatialSound = options.spatialSound || false;
  28691. this.maxDistance = options.maxDistance || 100;
  28692. this.useCustomAttenuation = options.useCustomAttenuation || false;
  28693. this.rolloffFactor = options.rolloffFactor || 1;
  28694. this.refDistance = options.refDistance || 1;
  28695. this.distanceModel = options.distanceModel || "linear";
  28696. this._playbackRate = options.playbackRate || 1;
  28697. }
  28698. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28699. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  28700. this._soundGain.gain.value = this._volume;
  28701. this._inputAudioNode = this._soundGain;
  28702. this._ouputAudioNode = this._soundGain;
  28703. if (this.spatialSound) {
  28704. this._createSpatialParameters();
  28705. }
  28706. this._scene.mainSoundTrack.AddSound(this);
  28707. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  28708. if (urlOrArrayBuffer) {
  28709. // If it's an URL
  28710. if (typeof (urlOrArrayBuffer) === "string") {
  28711. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  28712. _this._soundLoaded(data);
  28713. }, null, null, true);
  28714. }
  28715. else {
  28716. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  28717. this._soundLoaded(urlOrArrayBuffer);
  28718. }
  28719. else {
  28720. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  28721. }
  28722. }
  28723. }
  28724. }
  28725. else {
  28726. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  28727. this._scene.mainSoundTrack.AddSound(this);
  28728. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  28729. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  28730. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  28731. }
  28732. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  28733. if (this._readyToPlayCallback) {
  28734. window.setTimeout(function () {
  28735. _this._readyToPlayCallback();
  28736. }, 1000);
  28737. }
  28738. }
  28739. }
  28740. Sound.prototype.dispose = function () {
  28741. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  28742. if (this.isPlaying) {
  28743. this.stop();
  28744. }
  28745. this._isReadyToPlay = false;
  28746. if (this.soundTrackId === -1) {
  28747. this._scene.mainSoundTrack.RemoveSound(this);
  28748. }
  28749. else {
  28750. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  28751. }
  28752. if (this._soundGain) {
  28753. this._soundGain.disconnect();
  28754. this._soundGain = null;
  28755. }
  28756. if (this._soundPanner) {
  28757. this._soundPanner.disconnect();
  28758. this._soundPanner = null;
  28759. }
  28760. if (this._soundSource) {
  28761. this._soundSource.disconnect();
  28762. this._soundSource = null;
  28763. }
  28764. this._audioBuffer = null;
  28765. if (this._connectedMesh) {
  28766. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  28767. this._connectedMesh = null;
  28768. }
  28769. }
  28770. };
  28771. Sound.prototype._soundLoaded = function (audioData) {
  28772. var _this = this;
  28773. this._isLoaded = true;
  28774. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  28775. _this._audioBuffer = buffer;
  28776. _this._isReadyToPlay = true;
  28777. if (_this.autoplay) {
  28778. _this.play();
  28779. }
  28780. if (_this._readyToPlayCallback) {
  28781. _this._readyToPlayCallback();
  28782. }
  28783. }, function (error) {
  28784. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  28785. });
  28786. };
  28787. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  28788. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28789. this._audioBuffer = audioBuffer;
  28790. this._isReadyToPlay = true;
  28791. }
  28792. };
  28793. Sound.prototype.updateOptions = function (options) {
  28794. if (options) {
  28795. this.loop = options.loop || this.loop;
  28796. this.maxDistance = options.maxDistance || this.maxDistance;
  28797. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  28798. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  28799. this.refDistance = options.refDistance || this.refDistance;
  28800. this.distanceModel = options.distanceModel || this.distanceModel;
  28801. this._playbackRate = options.playbackRate || this._playbackRate;
  28802. }
  28803. };
  28804. Sound.prototype._createSpatialParameters = function () {
  28805. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28806. if (this._scene.headphone) {
  28807. this._panningModel = "HRTF";
  28808. }
  28809. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  28810. if (this.useCustomAttenuation) {
  28811. // Tricks to disable in a way embedded Web Audio attenuation
  28812. this._soundPanner.distanceModel = "linear";
  28813. this._soundPanner.maxDistance = Number.MAX_VALUE;
  28814. this._soundPanner.refDistance = 1;
  28815. this._soundPanner.rolloffFactor = 1;
  28816. this._soundPanner.panningModel = this._panningModel;
  28817. }
  28818. else {
  28819. this._soundPanner.distanceModel = this.distanceModel;
  28820. this._soundPanner.maxDistance = this.maxDistance;
  28821. this._soundPanner.refDistance = this.refDistance;
  28822. this._soundPanner.rolloffFactor = this.rolloffFactor;
  28823. this._soundPanner.panningModel = this._panningModel;
  28824. }
  28825. this._soundPanner.connect(this._ouputAudioNode);
  28826. this._inputAudioNode = this._soundPanner;
  28827. }
  28828. };
  28829. Sound.prototype.switchPanningModelToHRTF = function () {
  28830. this._panningModel = "HRTF";
  28831. this._switchPanningModel();
  28832. };
  28833. Sound.prototype.switchPanningModelToEqualPower = function () {
  28834. this._panningModel = "equalpower";
  28835. this._switchPanningModel();
  28836. };
  28837. Sound.prototype._switchPanningModel = function () {
  28838. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28839. this._soundPanner.panningModel = this._panningModel;
  28840. }
  28841. };
  28842. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  28843. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28844. this._ouputAudioNode.disconnect();
  28845. this._ouputAudioNode.connect(soundTrackAudioNode);
  28846. }
  28847. };
  28848. /**
  28849. * Transform this sound into a directional source
  28850. * @param coneInnerAngle Size of the inner cone in degree
  28851. * @param coneOuterAngle Size of the outer cone in degree
  28852. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  28853. */
  28854. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  28855. if (coneOuterAngle < coneInnerAngle) {
  28856. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  28857. return;
  28858. }
  28859. this._coneInnerAngle = coneInnerAngle;
  28860. this._coneOuterAngle = coneOuterAngle;
  28861. this._coneOuterGain = coneOuterGain;
  28862. this._isDirectional = true;
  28863. if (this.isPlaying && this.loop) {
  28864. this.stop();
  28865. this.play();
  28866. }
  28867. };
  28868. Sound.prototype.setPosition = function (newPosition) {
  28869. this._position = newPosition;
  28870. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28871. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28872. }
  28873. };
  28874. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  28875. this._localDirection = newLocalDirection;
  28876. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  28877. this._updateDirection();
  28878. }
  28879. };
  28880. Sound.prototype._updateDirection = function () {
  28881. var mat = this._connectedMesh.getWorldMatrix();
  28882. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  28883. direction.normalize();
  28884. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  28885. };
  28886. Sound.prototype.updateDistanceFromListener = function () {
  28887. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  28888. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  28889. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  28890. }
  28891. };
  28892. Sound.prototype.setAttenuationFunction = function (callback) {
  28893. this._customAttenuationFunction = callback;
  28894. };
  28895. /**
  28896. * Play the sound
  28897. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  28898. */
  28899. Sound.prototype.play = function (time) {
  28900. var _this = this;
  28901. if (this._isReadyToPlay && this._scene.audioEnabled) {
  28902. try {
  28903. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  28904. if (!this._soundSource) {
  28905. if (this.spatialSound) {
  28906. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28907. if (this._isDirectional) {
  28908. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  28909. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  28910. this._soundPanner.coneOuterGain = this._coneOuterGain;
  28911. if (this._connectedMesh) {
  28912. this._updateDirection();
  28913. }
  28914. else {
  28915. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  28916. }
  28917. }
  28918. }
  28919. }
  28920. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  28921. this._soundSource.buffer = this._audioBuffer;
  28922. this._soundSource.connect(this._inputAudioNode);
  28923. this._soundSource.loop = this.loop;
  28924. this._soundSource.playbackRate.value = this._playbackRate;
  28925. this._startTime = startTime;
  28926. this._soundSource.onended = function () {
  28927. _this._onended();
  28928. };
  28929. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  28930. this.isPlaying = true;
  28931. this.isPaused = false;
  28932. }
  28933. catch (ex) {
  28934. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  28935. }
  28936. }
  28937. };
  28938. Sound.prototype._onended = function () {
  28939. this.isPlaying = false;
  28940. if (this.onended) {
  28941. this.onended();
  28942. }
  28943. };
  28944. /**
  28945. * Stop the sound
  28946. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  28947. */
  28948. Sound.prototype.stop = function (time) {
  28949. if (this.isPlaying) {
  28950. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  28951. this._soundSource.stop(stopTime);
  28952. this.isPlaying = false;
  28953. }
  28954. };
  28955. Sound.prototype.pause = function () {
  28956. if (this.isPlaying) {
  28957. this.stop(0);
  28958. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  28959. this.isPaused = true;
  28960. }
  28961. };
  28962. Sound.prototype.setVolume = function (newVolume, time) {
  28963. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  28964. if (time) {
  28965. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  28966. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  28967. }
  28968. else {
  28969. this._soundGain.gain.value = newVolume;
  28970. }
  28971. }
  28972. this._volume = newVolume;
  28973. };
  28974. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  28975. this._playbackRate = newPlaybackRate;
  28976. if (this.isPlaying) {
  28977. this._soundSource.playbackRate.value = this._playbackRate;
  28978. }
  28979. };
  28980. Sound.prototype.getVolume = function () {
  28981. return this._volume;
  28982. };
  28983. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  28984. var _this = this;
  28985. this._connectedMesh = meshToConnectTo;
  28986. if (!this.spatialSound) {
  28987. this._createSpatialParameters();
  28988. this.spatialSound = true;
  28989. if (this.isPlaying && this.loop) {
  28990. this.stop();
  28991. this.play();
  28992. }
  28993. }
  28994. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  28995. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  28996. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  28997. };
  28998. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  28999. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  29000. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  29001. this._updateDirection();
  29002. }
  29003. };
  29004. return Sound;
  29005. })();
  29006. BABYLON.Sound = Sound;
  29007. })(BABYLON || (BABYLON = {}));
  29008. //# sourceMappingURL=babylon.sound.js.map
  29009. var BABYLON;
  29010. (function (BABYLON) {
  29011. var SoundTrack = (function () {
  29012. function SoundTrack(scene, options) {
  29013. this.id = -1;
  29014. this._isMainTrack = false;
  29015. this._scene = scene;
  29016. this._audioEngine = BABYLON.Engine.audioEngine;
  29017. this.soundCollection = new Array();
  29018. if (this._audioEngine.canUseWebAudio) {
  29019. this._trackGain = this._audioEngine.audioContext.createGain();
  29020. this._trackGain.connect(this._audioEngine.masterGain);
  29021. if (options) {
  29022. if (options.volume) {
  29023. this._trackGain.gain.value = options.volume;
  29024. }
  29025. if (options.mainTrack) {
  29026. this._isMainTrack = options.mainTrack;
  29027. }
  29028. }
  29029. }
  29030. if (!this._isMainTrack) {
  29031. this._scene.soundTracks.push(this);
  29032. this.id = this._scene.soundTracks.length - 1;
  29033. }
  29034. }
  29035. SoundTrack.prototype.dispose = function () {
  29036. if (this._audioEngine.canUseWebAudio) {
  29037. if (this._connectedAnalyser) {
  29038. this._connectedAnalyser.stopDebugCanvas();
  29039. }
  29040. while (this.soundCollection.length) {
  29041. this.soundCollection[0].dispose();
  29042. }
  29043. this._trackGain.disconnect();
  29044. this._trackGain = null;
  29045. }
  29046. };
  29047. SoundTrack.prototype.AddSound = function (sound) {
  29048. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29049. sound.connectToSoundTrackAudioNode(this._trackGain);
  29050. }
  29051. if (sound.soundTrackId) {
  29052. if (sound.soundTrackId === -1) {
  29053. this._scene.mainSoundTrack.RemoveSound(sound);
  29054. }
  29055. else {
  29056. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  29057. }
  29058. }
  29059. this.soundCollection.push(sound);
  29060. sound.soundTrackId = this.id;
  29061. };
  29062. SoundTrack.prototype.RemoveSound = function (sound) {
  29063. var index = this.soundCollection.indexOf(sound);
  29064. if (index !== -1) {
  29065. this.soundCollection.splice(index, 1);
  29066. }
  29067. };
  29068. SoundTrack.prototype.setVolume = function (newVolume) {
  29069. if (this._audioEngine.canUseWebAudio) {
  29070. this._trackGain.gain.value = newVolume;
  29071. }
  29072. };
  29073. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  29074. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29075. for (var i = 0; i < this.soundCollection.length; i++) {
  29076. this.soundCollection[i].switchPanningModelToHRTF();
  29077. }
  29078. }
  29079. };
  29080. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  29081. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29082. for (var i = 0; i < this.soundCollection.length; i++) {
  29083. this.soundCollection[i].switchPanningModelToEqualPower();
  29084. }
  29085. }
  29086. };
  29087. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  29088. if (this._connectedAnalyser) {
  29089. this._connectedAnalyser.stopDebugCanvas();
  29090. }
  29091. this._connectedAnalyser = analyser;
  29092. if (this._audioEngine.canUseWebAudio) {
  29093. this._trackGain.disconnect();
  29094. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  29095. }
  29096. };
  29097. return SoundTrack;
  29098. })();
  29099. BABYLON.SoundTrack = SoundTrack;
  29100. })(BABYLON || (BABYLON = {}));
  29101. //# sourceMappingURL=babylon.soundtrack.js.map
  29102. var BABYLON;
  29103. (function (BABYLON) {
  29104. var DebugLayer = (function () {
  29105. function DebugLayer(scene) {
  29106. var _this = this;
  29107. this._transformationMatrix = BABYLON.Matrix.Identity();
  29108. this._enabled = false;
  29109. this._labelsEnabled = false;
  29110. this._displayStatistics = true;
  29111. this._displayTree = false;
  29112. this._displayLogs = false;
  29113. this._identityMatrix = BABYLON.Matrix.Identity();
  29114. this.axisRatio = 0.02;
  29115. this.accentColor = "orange";
  29116. this._scene = scene;
  29117. this._syncPositions = function () {
  29118. var engine = _this._scene.getEngine();
  29119. var canvasRect = engine.getRenderingCanvasClientRect();
  29120. if (_this._showUI) {
  29121. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29122. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29123. _this._statsDiv.style.width = "400px";
  29124. _this._statsDiv.style.height = "auto";
  29125. _this._statsSubsetDiv.style.maxHeight = "240px";
  29126. _this._optionsDiv.style.left = "0px";
  29127. _this._optionsDiv.style.top = "10px";
  29128. _this._optionsDiv.style.width = "200px";
  29129. _this._optionsDiv.style.height = "auto";
  29130. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29131. _this._logDiv.style.left = "0px";
  29132. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29133. _this._logDiv.style.width = "600px";
  29134. _this._logDiv.style.height = "160px";
  29135. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29136. _this._treeDiv.style.top = "10px";
  29137. _this._treeDiv.style.width = "300px";
  29138. _this._treeDiv.style.height = "auto";
  29139. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29140. }
  29141. _this._globalDiv.style.left = canvasRect.left + "px";
  29142. _this._globalDiv.style.top = canvasRect.top + "px";
  29143. _this._drawingCanvas.style.left = "0px";
  29144. _this._drawingCanvas.style.top = "0px";
  29145. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29146. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29147. var devicePixelRatio = window.devicePixelRatio || 1;
  29148. var context = _this._drawingContext;
  29149. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  29150. _this._ratio = devicePixelRatio / backingStoreRatio;
  29151. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29152. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29153. };
  29154. this._onCanvasClick = function (evt) {
  29155. _this._clickPosition = {
  29156. x: evt.clientX * _this._ratio,
  29157. y: evt.clientY * _this._ratio
  29158. };
  29159. };
  29160. this._syncUI = function () {
  29161. if (_this._showUI) {
  29162. if (_this._displayStatistics) {
  29163. _this._displayStats();
  29164. _this._statsDiv.style.display = "";
  29165. }
  29166. else {
  29167. _this._statsDiv.style.display = "none";
  29168. }
  29169. if (_this._displayLogs) {
  29170. _this._logDiv.style.display = "";
  29171. }
  29172. else {
  29173. _this._logDiv.style.display = "none";
  29174. }
  29175. if (_this._displayTree) {
  29176. _this._treeDiv.style.display = "";
  29177. if (_this._needToRefreshMeshesTree) {
  29178. _this._needToRefreshMeshesTree = false;
  29179. _this._refreshMeshesTreeContent();
  29180. }
  29181. }
  29182. else {
  29183. _this._treeDiv.style.display = "none";
  29184. }
  29185. }
  29186. };
  29187. this._syncData = function () {
  29188. if (_this._labelsEnabled || !_this._showUI) {
  29189. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29190. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29191. var engine = _this._scene.getEngine();
  29192. var viewport = _this._camera.viewport;
  29193. var globalViewport = viewport.toGlobal(engine);
  29194. // Meshes
  29195. var meshes = _this._camera.getActiveMeshes();
  29196. for (var index = 0; index < meshes.length; index++) {
  29197. var mesh = meshes.data[index];
  29198. var position = mesh.getBoundingInfo().boundingSphere.center;
  29199. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29200. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29201. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29202. }
  29203. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29204. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  29205. mesh.renderOverlay = !mesh.renderOverlay;
  29206. }, function () {
  29207. return mesh.renderOverlay ? 'red' : 'black';
  29208. });
  29209. }
  29210. }
  29211. // Cameras
  29212. var cameras = _this._scene.cameras;
  29213. for (index = 0; index < cameras.length; index++) {
  29214. var camera = cameras[index];
  29215. if (camera === _this._camera) {
  29216. continue;
  29217. }
  29218. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29219. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29220. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29221. _this._camera.detachControl(engine.getRenderingCanvas());
  29222. _this._camera = camera;
  29223. _this._camera.attachControl(engine.getRenderingCanvas());
  29224. }, function () {
  29225. return "purple";
  29226. });
  29227. }
  29228. }
  29229. // Lights
  29230. var lights = _this._scene.lights;
  29231. for (index = 0; index < lights.length; index++) {
  29232. var light = lights[index];
  29233. if (light.position) {
  29234. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29235. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29236. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29237. light.setEnabled(!light.isEnabled());
  29238. }, function () {
  29239. return light.isEnabled() ? "orange" : "gray";
  29240. });
  29241. }
  29242. }
  29243. }
  29244. }
  29245. _this._clickPosition = undefined;
  29246. };
  29247. }
  29248. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29249. while (this._treeSubsetDiv.hasChildNodes()) {
  29250. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29251. }
  29252. // Add meshes
  29253. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29254. sortedArray.sort(function (a, b) {
  29255. if (a.name === b.name) {
  29256. return 0;
  29257. }
  29258. return (a.name > b.name) ? 1 : -1;
  29259. });
  29260. for (var index = 0; index < sortedArray.length; index++) {
  29261. var mesh = sortedArray[index];
  29262. if (!mesh.isEnabled()) {
  29263. continue;
  29264. }
  29265. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29266. m.isVisible = element.checked;
  29267. }, mesh);
  29268. }
  29269. };
  29270. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29271. this._drawingContext.beginPath();
  29272. this._drawingContext.moveTo(zero.x, zero.y);
  29273. this._drawingContext.lineTo(unit.x, unit.y);
  29274. this._drawingContext.strokeStyle = color;
  29275. this._drawingContext.lineWidth = 4;
  29276. this._drawingContext.stroke();
  29277. this._drawingContext.font = "normal 14px Segoe UI";
  29278. this._drawingContext.fillStyle = color;
  29279. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29280. };
  29281. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29282. var position = mesh.getBoundingInfo().boundingSphere.center;
  29283. var worldMatrix = mesh.getWorldMatrix();
  29284. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29285. var unit = (unprojectedVector.subtract(position)).length();
  29286. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29287. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29288. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29289. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29290. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29291. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29292. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29293. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29294. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29295. };
  29296. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29297. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29298. this._drawingContext.font = "normal 12px Segoe UI";
  29299. var textMetrics = this._drawingContext.measureText(text);
  29300. var centerX = projectedPosition.x - textMetrics.width / 2;
  29301. var centerY = projectedPosition.y;
  29302. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29303. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29304. onClick();
  29305. }
  29306. this._drawingContext.beginPath();
  29307. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29308. this._drawingContext.fillStyle = getFillStyle();
  29309. this._drawingContext.globalAlpha = 0.5;
  29310. this._drawingContext.fill();
  29311. this._drawingContext.globalAlpha = 1.0;
  29312. this._drawingContext.strokeStyle = '#FFFFFF';
  29313. this._drawingContext.lineWidth = 1;
  29314. this._drawingContext.stroke();
  29315. this._drawingContext.fillStyle = "#FFFFFF";
  29316. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29317. this._drawingContext.beginPath();
  29318. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29319. this._drawingContext.fill();
  29320. }
  29321. };
  29322. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29323. if (!this._clickPosition) {
  29324. return false;
  29325. }
  29326. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29327. return false;
  29328. }
  29329. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29330. return false;
  29331. }
  29332. return true;
  29333. };
  29334. DebugLayer.prototype.isVisible = function () {
  29335. return this._enabled;
  29336. };
  29337. DebugLayer.prototype.hide = function () {
  29338. if (!this._enabled) {
  29339. return;
  29340. }
  29341. this._enabled = false;
  29342. var engine = this._scene.getEngine();
  29343. this._scene.unregisterBeforeRender(this._syncData);
  29344. this._scene.unregisterAfterRender(this._syncUI);
  29345. document.body.removeChild(this._globalDiv);
  29346. window.removeEventListener("resize", this._syncPositions);
  29347. this._scene.forceShowBoundingBoxes = false;
  29348. this._scene.forceWireframe = false;
  29349. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29350. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29351. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29352. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29353. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29354. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29355. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29356. this._scene.shadowsEnabled = true;
  29357. this._scene.particlesEnabled = true;
  29358. this._scene.postProcessesEnabled = true;
  29359. this._scene.collisionsEnabled = true;
  29360. this._scene.lightsEnabled = true;
  29361. this._scene.texturesEnabled = true;
  29362. this._scene.lensFlaresEnabled = true;
  29363. this._scene.proceduralTexturesEnabled = true;
  29364. this._scene.renderTargetsEnabled = true;
  29365. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29366. };
  29367. DebugLayer.prototype.show = function (showUI, camera) {
  29368. if (showUI === void 0) { showUI = true; }
  29369. if (camera === void 0) { camera = null; }
  29370. if (this._enabled) {
  29371. return;
  29372. }
  29373. this._enabled = true;
  29374. if (camera) {
  29375. this._camera = camera;
  29376. }
  29377. else {
  29378. this._camera = this._scene.activeCamera;
  29379. }
  29380. this._showUI = showUI;
  29381. var engine = this._scene.getEngine();
  29382. this._globalDiv = document.createElement("div");
  29383. document.body.appendChild(this._globalDiv);
  29384. this._generateDOMelements();
  29385. window.addEventListener("resize", this._syncPositions);
  29386. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29387. this._syncPositions();
  29388. this._scene.registerBeforeRender(this._syncData);
  29389. this._scene.registerAfterRender(this._syncUI);
  29390. };
  29391. DebugLayer.prototype._clearLabels = function () {
  29392. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29393. for (var index = 0; index < this._scene.meshes.length; index++) {
  29394. var mesh = this._scene.meshes[index];
  29395. mesh.renderOverlay = false;
  29396. }
  29397. };
  29398. DebugLayer.prototype._generateheader = function (root, text) {
  29399. var header = document.createElement("div");
  29400. header.innerHTML = text + "&nbsp;";
  29401. header.style.textAlign = "right";
  29402. header.style.width = "100%";
  29403. header.style.color = "white";
  29404. header.style.backgroundColor = "Black";
  29405. header.style.padding = "5px 5px 4px 0px";
  29406. header.style.marginLeft = "-5px";
  29407. header.style.fontWeight = "bold";
  29408. root.appendChild(header);
  29409. };
  29410. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29411. var label = document.createElement("label");
  29412. label.innerHTML = title;
  29413. label.style.color = color;
  29414. root.appendChild(label);
  29415. root.appendChild(document.createElement("br"));
  29416. };
  29417. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29418. if (tag === void 0) { tag = null; }
  29419. var label = document.createElement("label");
  29420. var boundingBoxesCheckbox = document.createElement("input");
  29421. boundingBoxesCheckbox.type = "checkbox";
  29422. boundingBoxesCheckbox.checked = initialState;
  29423. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29424. task(evt.target, tag);
  29425. });
  29426. label.appendChild(boundingBoxesCheckbox);
  29427. var container = document.createElement("span");
  29428. var leftPart = document.createElement("span");
  29429. var rightPart = document.createElement("span");
  29430. rightPart.style.cssFloat = "right";
  29431. leftPart.innerHTML = leftTitle;
  29432. rightPart.innerHTML = rightTitle;
  29433. rightPart.style.fontSize = "12px";
  29434. rightPart.style.maxWidth = "200px";
  29435. container.appendChild(leftPart);
  29436. container.appendChild(rightPart);
  29437. label.appendChild(container);
  29438. root.appendChild(label);
  29439. root.appendChild(document.createElement("br"));
  29440. };
  29441. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29442. if (tag === void 0) { tag = null; }
  29443. var label = document.createElement("label");
  29444. var checkBox = document.createElement("input");
  29445. checkBox.type = "checkbox";
  29446. checkBox.checked = initialState;
  29447. checkBox.addEventListener("change", function (evt) {
  29448. task(evt.target, tag);
  29449. });
  29450. label.appendChild(checkBox);
  29451. label.appendChild(document.createTextNode(title));
  29452. root.appendChild(label);
  29453. root.appendChild(document.createElement("br"));
  29454. };
  29455. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29456. if (tag === void 0) { tag = null; }
  29457. var button = document.createElement("button");
  29458. button.innerHTML = title;
  29459. button.style.height = "24px";
  29460. button.style.color = "#444444";
  29461. button.style.border = "1px solid white";
  29462. button.className = "debugLayerButton";
  29463. button.addEventListener("click", function (evt) {
  29464. task(evt.target, tag);
  29465. });
  29466. root.appendChild(button);
  29467. root.appendChild(document.createElement("br"));
  29468. };
  29469. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29470. if (tag === void 0) { tag = null; }
  29471. var label = document.createElement("label");
  29472. var boundingBoxesRadio = document.createElement("input");
  29473. boundingBoxesRadio.type = "radio";
  29474. boundingBoxesRadio.name = name;
  29475. boundingBoxesRadio.checked = initialState;
  29476. boundingBoxesRadio.addEventListener("change", function (evt) {
  29477. task(evt.target, tag);
  29478. });
  29479. label.appendChild(boundingBoxesRadio);
  29480. label.appendChild(document.createTextNode(title));
  29481. root.appendChild(label);
  29482. root.appendChild(document.createElement("br"));
  29483. };
  29484. DebugLayer.prototype._generateDOMelements = function () {
  29485. var _this = this;
  29486. this._globalDiv.id = "DebugLayer";
  29487. this._globalDiv.style.position = "absolute";
  29488. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29489. this._globalDiv.style.fontSize = "14px";
  29490. this._globalDiv.style.color = "white";
  29491. // Drawing canvas
  29492. this._drawingCanvas = document.createElement("canvas");
  29493. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29494. this._drawingCanvas.style.position = "absolute";
  29495. this._drawingCanvas.style.pointerEvents = "none";
  29496. this._drawingContext = this._drawingCanvas.getContext("2d");
  29497. this._globalDiv.appendChild(this._drawingCanvas);
  29498. if (this._showUI) {
  29499. var background = "rgba(128, 128, 128, 0.4)";
  29500. var border = "rgb(180, 180, 180) solid 1px";
  29501. // Stats
  29502. this._statsDiv = document.createElement("div");
  29503. this._statsDiv.id = "DebugLayerStats";
  29504. this._statsDiv.style.border = border;
  29505. this._statsDiv.style.position = "absolute";
  29506. this._statsDiv.style.background = background;
  29507. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29508. this._generateheader(this._statsDiv, "STATISTICS");
  29509. this._statsSubsetDiv = document.createElement("div");
  29510. this._statsSubsetDiv.style.paddingTop = "5px";
  29511. this._statsSubsetDiv.style.paddingBottom = "5px";
  29512. this._statsSubsetDiv.style.overflowY = "auto";
  29513. this._statsDiv.appendChild(this._statsSubsetDiv);
  29514. // Tree
  29515. this._treeDiv = document.createElement("div");
  29516. this._treeDiv.id = "DebugLayerTree";
  29517. this._treeDiv.style.border = border;
  29518. this._treeDiv.style.position = "absolute";
  29519. this._treeDiv.style.background = background;
  29520. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29521. this._treeDiv.style.display = "none";
  29522. this._generateheader(this._treeDiv, "MESHES TREE");
  29523. this._treeSubsetDiv = document.createElement("div");
  29524. this._treeSubsetDiv.style.paddingTop = "5px";
  29525. this._treeSubsetDiv.style.paddingRight = "5px";
  29526. this._treeSubsetDiv.style.overflowY = "auto";
  29527. this._treeSubsetDiv.style.maxHeight = "300px";
  29528. this._treeDiv.appendChild(this._treeSubsetDiv);
  29529. this._needToRefreshMeshesTree = true;
  29530. // Logs
  29531. this._logDiv = document.createElement("div");
  29532. this._logDiv.style.border = border;
  29533. this._logDiv.id = "DebugLayerLogs";
  29534. this._logDiv.style.position = "absolute";
  29535. this._logDiv.style.background = background;
  29536. this._logDiv.style.padding = "0px 0px 0px 5px";
  29537. this._logDiv.style.display = "none";
  29538. this._generateheader(this._logDiv, "LOGS");
  29539. this._logSubsetDiv = document.createElement("div");
  29540. this._logSubsetDiv.style.height = "127px";
  29541. this._logSubsetDiv.style.paddingTop = "5px";
  29542. this._logSubsetDiv.style.overflowY = "auto";
  29543. this._logSubsetDiv.style.fontSize = "12px";
  29544. this._logSubsetDiv.style.fontFamily = "consolas";
  29545. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29546. this._logDiv.appendChild(this._logSubsetDiv);
  29547. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29548. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29549. };
  29550. // Options
  29551. this._optionsDiv = document.createElement("div");
  29552. this._optionsDiv.id = "DebugLayerOptions";
  29553. this._optionsDiv.style.border = border;
  29554. this._optionsDiv.style.position = "absolute";
  29555. this._optionsDiv.style.background = background;
  29556. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29557. this._optionsDiv.style.overflowY = "auto";
  29558. this._generateheader(this._optionsDiv, "OPTIONS");
  29559. this._optionsSubsetDiv = document.createElement("div");
  29560. this._optionsSubsetDiv.style.paddingTop = "5px";
  29561. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29562. this._optionsSubsetDiv.style.overflowY = "auto";
  29563. this._optionsSubsetDiv.style.maxHeight = "200px";
  29564. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29565. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29566. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  29567. _this._displayStatistics = element.checked;
  29568. });
  29569. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  29570. _this._displayLogs = element.checked;
  29571. });
  29572. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29573. _this._displayTree = element.checked;
  29574. _this._needToRefreshMeshesTree = true;
  29575. });
  29576. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29577. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29578. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  29579. _this._scene.forceShowBoundingBoxes = element.checked;
  29580. });
  29581. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29582. _this._labelsEnabled = element.checked;
  29583. if (!_this._labelsEnabled) {
  29584. _this._clearLabels();
  29585. }
  29586. });
  29587. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29588. if (element.checked) {
  29589. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29590. }
  29591. else {
  29592. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29593. }
  29594. });
  29595. ;
  29596. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29597. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29598. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29599. if (element.checked) {
  29600. _this._scene.forceWireframe = false;
  29601. _this._scene.forcePointsCloud = false;
  29602. }
  29603. });
  29604. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29605. if (element.checked) {
  29606. _this._scene.forceWireframe = true;
  29607. _this._scene.forcePointsCloud = false;
  29608. }
  29609. });
  29610. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29611. if (element.checked) {
  29612. _this._scene.forceWireframe = false;
  29613. _this._scene.forcePointsCloud = true;
  29614. }
  29615. });
  29616. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29617. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29618. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  29619. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  29620. });
  29621. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  29622. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  29623. });
  29624. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  29625. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  29626. });
  29627. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  29628. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  29629. });
  29630. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  29631. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  29632. });
  29633. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  29634. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  29635. });
  29636. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  29637. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  29638. });
  29639. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  29640. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  29641. });
  29642. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29643. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29644. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  29645. _this._scene.animationsEnabled = element.checked;
  29646. });
  29647. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  29648. _this._scene.collisionsEnabled = element.checked;
  29649. });
  29650. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  29651. _this._scene.fogEnabled = element.checked;
  29652. });
  29653. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  29654. _this._scene.lensFlaresEnabled = element.checked;
  29655. });
  29656. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  29657. _this._scene.lightsEnabled = element.checked;
  29658. });
  29659. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  29660. _this._scene.particlesEnabled = element.checked;
  29661. });
  29662. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  29663. _this._scene.postProcessesEnabled = element.checked;
  29664. });
  29665. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  29666. _this._scene.proceduralTexturesEnabled = element.checked;
  29667. });
  29668. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  29669. _this._scene.renderTargetsEnabled = element.checked;
  29670. });
  29671. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  29672. _this._scene.shadowsEnabled = element.checked;
  29673. });
  29674. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  29675. _this._scene.skeletonsEnabled = element.checked;
  29676. });
  29677. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  29678. _this._scene.spritesEnabled = element.checked;
  29679. });
  29680. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  29681. _this._scene.texturesEnabled = element.checked;
  29682. });
  29683. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29684. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29685. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29686. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29687. if (element.checked) {
  29688. _this._scene.headphone = true;
  29689. }
  29690. });
  29691. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29692. if (element.checked) {
  29693. _this._scene.headphone = false;
  29694. }
  29695. });
  29696. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29697. _this._scene.audioEnabled = !element.checked;
  29698. });
  29699. }
  29700. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29701. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29702. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  29703. _this._scene.dumpNextRenderTargets = true;
  29704. });
  29705. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29706. this._globalDiv.appendChild(this._statsDiv);
  29707. this._globalDiv.appendChild(this._logDiv);
  29708. this._globalDiv.appendChild(this._optionsDiv);
  29709. this._globalDiv.appendChild(this._treeDiv);
  29710. }
  29711. };
  29712. DebugLayer.prototype._displayStats = function () {
  29713. var scene = this._scene;
  29714. var engine = scene.getEngine();
  29715. var glInfo = engine.getGlInfo();
  29716. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Count</b><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Total materials: " + scene.materials.length + "<br>" + "Total textures: " + scene.textures.length + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active indices: " + scene.getActiveIndices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<b>Duration</b><br>" + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>" + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>" + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>" + "</div>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Extensions</b><br>" + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>" + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>" + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>" + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>" + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>" + "<b>Caps.</b><br>" + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>" + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>" + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>" + "</div><br>" + "<b>Info</b><br>" + glInfo.version + "<br>" + glInfo.renderer + "<br>";
  29717. if (this.customStatsFunction) {
  29718. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29719. }
  29720. };
  29721. return DebugLayer;
  29722. })();
  29723. BABYLON.DebugLayer = DebugLayer;
  29724. })(BABYLON || (BABYLON = {}));
  29725. //# sourceMappingURL=babylon.debugLayer.js.map
  29726. var __extends = this.__extends || function (d, b) {
  29727. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  29728. function __() { this.constructor = d; }
  29729. __.prototype = b.prototype;
  29730. d.prototype = new __();
  29731. };
  29732. var BABYLON;
  29733. (function (BABYLON) {
  29734. var RawTexture = (function (_super) {
  29735. __extends(RawTexture, _super);
  29736. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  29737. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29738. if (invertY === void 0) { invertY = false; }
  29739. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29740. _super.call(this, null, scene, !generateMipMaps, invertY);
  29741. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  29742. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29743. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29744. }
  29745. // Statics
  29746. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29747. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29748. if (invertY === void 0) { invertY = false; }
  29749. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29750. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  29751. };
  29752. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29753. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29754. if (invertY === void 0) { invertY = false; }
  29755. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29756. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29757. };
  29758. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29759. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29760. if (invertY === void 0) { invertY = false; }
  29761. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29762. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29763. };
  29764. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29765. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29766. if (invertY === void 0) { invertY = false; }
  29767. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29768. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  29769. };
  29770. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29771. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29772. if (invertY === void 0) { invertY = false; }
  29773. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29774. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  29775. };
  29776. return RawTexture;
  29777. })(BABYLON.Texture);
  29778. BABYLON.RawTexture = RawTexture;
  29779. })(BABYLON || (BABYLON = {}));
  29780. //# sourceMappingURL=babylon.rawTexture.js.map
  29781. var __extends = this.__extends || function (d, b) {
  29782. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  29783. function __() { this.constructor = d; }
  29784. __.prototype = b.prototype;
  29785. d.prototype = new __();
  29786. };
  29787. var BABYLON;
  29788. (function (BABYLON) {
  29789. var IndexedVector2 = (function (_super) {
  29790. __extends(IndexedVector2, _super);
  29791. function IndexedVector2(original, index) {
  29792. _super.call(this, original.x, original.y);
  29793. this.index = index;
  29794. }
  29795. return IndexedVector2;
  29796. })(BABYLON.Vector2);
  29797. var PolygonPoints = (function () {
  29798. function PolygonPoints() {
  29799. this.elements = new Array();
  29800. }
  29801. PolygonPoints.prototype.add = function (originalPoints) {
  29802. var _this = this;
  29803. var result = new Array();
  29804. originalPoints.forEach(function (point) {
  29805. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  29806. var newPoint = new IndexedVector2(point, _this.elements.length);
  29807. result.push(newPoint);
  29808. _this.elements.push(newPoint);
  29809. }
  29810. });
  29811. return result;
  29812. };
  29813. PolygonPoints.prototype.computeBounds = function () {
  29814. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29815. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29816. this.elements.forEach(function (point) {
  29817. // x
  29818. if (point.x < lmin.x) {
  29819. lmin.x = point.x;
  29820. }
  29821. else if (point.x > lmax.x) {
  29822. lmax.x = point.x;
  29823. }
  29824. // y
  29825. if (point.y < lmin.y) {
  29826. lmin.y = point.y;
  29827. }
  29828. else if (point.y > lmax.y) {
  29829. lmax.y = point.y;
  29830. }
  29831. });
  29832. return {
  29833. min: lmin,
  29834. max: lmax,
  29835. width: lmax.x - lmin.x,
  29836. height: lmax.y - lmin.y
  29837. };
  29838. };
  29839. return PolygonPoints;
  29840. })();
  29841. var Polygon = (function () {
  29842. function Polygon() {
  29843. }
  29844. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  29845. return [
  29846. new BABYLON.Vector2(xmin, ymin),
  29847. new BABYLON.Vector2(xmax, ymin),
  29848. new BABYLON.Vector2(xmax, ymax),
  29849. new BABYLON.Vector2(xmin, ymax)
  29850. ];
  29851. };
  29852. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  29853. if (cx === void 0) { cx = 0; }
  29854. if (cy === void 0) { cy = 0; }
  29855. if (numberOfSides === void 0) { numberOfSides = 32; }
  29856. var result = new Array();
  29857. var angle = 0;
  29858. var increment = (Math.PI * 2) / numberOfSides;
  29859. for (var i = 0; i < numberOfSides; i++) {
  29860. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  29861. angle -= increment;
  29862. }
  29863. return result;
  29864. };
  29865. Polygon.Parse = function (input) {
  29866. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  29867. var i, result = [];
  29868. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  29869. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  29870. }
  29871. return result;
  29872. };
  29873. Polygon.StartingAt = function (x, y) {
  29874. return BABYLON.Path2.StartingAt(x, y);
  29875. };
  29876. return Polygon;
  29877. })();
  29878. BABYLON.Polygon = Polygon;
  29879. var PolygonMeshBuilder = (function () {
  29880. function PolygonMeshBuilder(name, contours, scene) {
  29881. this._points = new PolygonPoints();
  29882. this._outlinepoints = new PolygonPoints();
  29883. this._holes = [];
  29884. if (!("poly2tri" in window)) {
  29885. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  29886. }
  29887. this._name = name;
  29888. this._scene = scene;
  29889. var points;
  29890. if (contours instanceof BABYLON.Path2) {
  29891. points = contours.getPoints();
  29892. }
  29893. else {
  29894. points = contours;
  29895. }
  29896. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  29897. this._outlinepoints.add(points);
  29898. }
  29899. PolygonMeshBuilder.prototype.addHole = function (hole) {
  29900. this._swctx.addHole(this._points.add(hole));
  29901. var holepoints = new PolygonPoints();
  29902. holepoints.add(hole);
  29903. this._holes.push(holepoints);
  29904. return this;
  29905. };
  29906. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  29907. var _this = this;
  29908. if (updatable === void 0) { updatable = false; }
  29909. var result = new BABYLON.Mesh(this._name, this._scene);
  29910. var normals = [];
  29911. var positions = [];
  29912. var uvs = [];
  29913. var bounds = this._points.computeBounds();
  29914. this._points.elements.forEach(function (p) {
  29915. normals.push(0, 1.0, 0);
  29916. positions.push(p.x, 0, p.y);
  29917. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  29918. });
  29919. var indices = [];
  29920. this._swctx.triangulate();
  29921. this._swctx.getTriangles().forEach(function (triangle) {
  29922. triangle.getPoints().forEach(function (point) {
  29923. indices.push(point.index);
  29924. });
  29925. });
  29926. if (depth > 0) {
  29927. var positionscount = (positions.length / 3); //get the current pointcount
  29928. this._points.elements.forEach(function (p) {
  29929. normals.push(0, -1.0, 0);
  29930. positions.push(p.x, -depth, p.y);
  29931. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  29932. });
  29933. var p1; //we need to change order of point so the triangles are made in the rigth way.
  29934. var p2;
  29935. var poscounter = 0;
  29936. this._swctx.getTriangles().forEach(function (triangle) {
  29937. triangle.getPoints().forEach(function (point) {
  29938. switch (poscounter) {
  29939. case 0:
  29940. p1 = point;
  29941. break;
  29942. case 1:
  29943. p2 = point;
  29944. break;
  29945. case 2:
  29946. indices.push(point.index + positionscount);
  29947. indices.push(p2.index + positionscount);
  29948. indices.push(p1.index + positionscount);
  29949. poscounter = -1;
  29950. break;
  29951. }
  29952. poscounter++;
  29953. //indices.push((<IndexedVector2>point).index + positionscount);
  29954. });
  29955. });
  29956. //Add the sides
  29957. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  29958. this._holes.forEach(function (hole) {
  29959. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  29960. });
  29961. }
  29962. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  29963. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  29964. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  29965. result.setIndices(indices);
  29966. return result;
  29967. };
  29968. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  29969. var StartIndex = positions.length / 3;
  29970. var ulength = 0;
  29971. for (var i = 0; i < points.elements.length; i++) {
  29972. var p = points.elements[i];
  29973. var p1;
  29974. if ((i + 1) > points.elements.length - 1) {
  29975. p1 = points.elements[0];
  29976. }
  29977. else {
  29978. p1 = points.elements[i + 1];
  29979. }
  29980. positions.push(p.x, 0, p.y);
  29981. positions.push(p.x, -depth, p.y);
  29982. positions.push(p1.x, 0, p1.y);
  29983. positions.push(p1.x, -depth, p1.y);
  29984. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  29985. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  29986. var v3 = v2.subtract(v1);
  29987. var v4 = new BABYLON.Vector3(0, 1, 0);
  29988. var vn = BABYLON.Vector3.Cross(v3, v4);
  29989. vn = vn.normalize();
  29990. uvs.push(ulength / bounds.width, 0);
  29991. uvs.push(ulength / bounds.width, 1);
  29992. ulength += v3.length();
  29993. uvs.push((ulength / bounds.width), 0);
  29994. uvs.push((ulength / bounds.width), 1);
  29995. if (!flip) {
  29996. normals.push(-vn.x, -vn.y, -vn.z);
  29997. normals.push(-vn.x, -vn.y, -vn.z);
  29998. normals.push(-vn.x, -vn.y, -vn.z);
  29999. normals.push(-vn.x, -vn.y, -vn.z);
  30000. indices.push(StartIndex);
  30001. indices.push(StartIndex + 1);
  30002. indices.push(StartIndex + 2);
  30003. indices.push(StartIndex + 1);
  30004. indices.push(StartIndex + 3);
  30005. indices.push(StartIndex + 2);
  30006. }
  30007. else {
  30008. normals.push(vn.x, vn.y, vn.z);
  30009. normals.push(vn.x, vn.y, vn.z);
  30010. normals.push(vn.x, vn.y, vn.z);
  30011. normals.push(vn.x, vn.y, vn.z);
  30012. indices.push(StartIndex);
  30013. indices.push(StartIndex + 2);
  30014. indices.push(StartIndex + 1);
  30015. indices.push(StartIndex + 1);
  30016. indices.push(StartIndex + 2);
  30017. indices.push(StartIndex + 3);
  30018. }
  30019. StartIndex += 4;
  30020. }
  30021. ;
  30022. };
  30023. return PolygonMeshBuilder;
  30024. })();
  30025. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  30026. })(BABYLON || (BABYLON = {}));
  30027. //# sourceMappingURL=babylon.polygonMesh.js.map
  30028. var BABYLON;
  30029. (function (BABYLON) {
  30030. var SimplificationSettings = (function () {
  30031. function SimplificationSettings(quality, distance, optimizeMesh) {
  30032. this.quality = quality;
  30033. this.distance = distance;
  30034. this.optimizeMesh = optimizeMesh;
  30035. }
  30036. return SimplificationSettings;
  30037. })();
  30038. BABYLON.SimplificationSettings = SimplificationSettings;
  30039. var SimplificationQueue = (function () {
  30040. function SimplificationQueue() {
  30041. this.running = false;
  30042. this._simplificationArray = [];
  30043. }
  30044. SimplificationQueue.prototype.addTask = function (task) {
  30045. this._simplificationArray.push(task);
  30046. };
  30047. SimplificationQueue.prototype.executeNext = function () {
  30048. var task = this._simplificationArray.pop();
  30049. if (task) {
  30050. this.running = true;
  30051. this.runSimplification(task);
  30052. }
  30053. else {
  30054. this.running = false;
  30055. }
  30056. };
  30057. SimplificationQueue.prototype.runSimplification = function (task) {
  30058. var _this = this;
  30059. if (task.parallelProcessing) {
  30060. //parallel simplifier
  30061. task.settings.forEach(function (setting) {
  30062. var simplifier = _this.getSimplifier(task);
  30063. simplifier.simplify(setting, function (newMesh) {
  30064. task.mesh.addLODLevel(setting.distance, newMesh);
  30065. newMesh.isVisible = true;
  30066. //check if it is the last
  30067. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30068. //all done, run the success callback.
  30069. task.successCallback();
  30070. }
  30071. _this.executeNext();
  30072. });
  30073. });
  30074. }
  30075. else {
  30076. //single simplifier.
  30077. var simplifier = this.getSimplifier(task);
  30078. var runDecimation = function (setting, callback) {
  30079. simplifier.simplify(setting, function (newMesh) {
  30080. task.mesh.addLODLevel(setting.distance, newMesh);
  30081. newMesh.isVisible = true;
  30082. //run the next quality level
  30083. callback();
  30084. });
  30085. };
  30086. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30087. runDecimation(task.settings[loop.index], function () {
  30088. loop.executeNext();
  30089. });
  30090. }, function () {
  30091. //execution ended, run the success callback.
  30092. if (task.successCallback) {
  30093. task.successCallback();
  30094. }
  30095. _this.executeNext();
  30096. });
  30097. }
  30098. };
  30099. SimplificationQueue.prototype.getSimplifier = function (task) {
  30100. switch (task.simplificationType) {
  30101. case 0 /* QUADRATIC */:
  30102. default:
  30103. return new QuadraticErrorSimplification(task.mesh);
  30104. }
  30105. };
  30106. return SimplificationQueue;
  30107. })();
  30108. BABYLON.SimplificationQueue = SimplificationQueue;
  30109. /**
  30110. * The implemented types of simplification.
  30111. * At the moment only Quadratic Error Decimation is implemented.
  30112. */
  30113. (function (SimplificationType) {
  30114. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30115. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30116. var SimplificationType = BABYLON.SimplificationType;
  30117. var DecimationTriangle = (function () {
  30118. function DecimationTriangle(vertices) {
  30119. this.vertices = vertices;
  30120. this.error = new Array(4);
  30121. this.deleted = false;
  30122. this.isDirty = false;
  30123. this.deletePending = false;
  30124. this.borderFactor = 0;
  30125. }
  30126. return DecimationTriangle;
  30127. })();
  30128. BABYLON.DecimationTriangle = DecimationTriangle;
  30129. var DecimationVertex = (function () {
  30130. function DecimationVertex(position, id) {
  30131. this.position = position;
  30132. this.id = id;
  30133. this.isBorder = true;
  30134. this.q = new QuadraticMatrix();
  30135. this.triangleCount = 0;
  30136. this.triangleStart = 0;
  30137. this.originalOffsets = [];
  30138. }
  30139. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30140. this.position.copyFrom(newPosition);
  30141. };
  30142. return DecimationVertex;
  30143. })();
  30144. BABYLON.DecimationVertex = DecimationVertex;
  30145. var QuadraticMatrix = (function () {
  30146. function QuadraticMatrix(data) {
  30147. this.data = new Array(10);
  30148. for (var i = 0; i < 10; ++i) {
  30149. if (data && data[i]) {
  30150. this.data[i] = data[i];
  30151. }
  30152. else {
  30153. this.data[i] = 0;
  30154. }
  30155. }
  30156. }
  30157. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30158. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30159. return det;
  30160. };
  30161. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30162. for (var i = 0; i < 10; ++i) {
  30163. this.data[i] += matrix.data[i];
  30164. }
  30165. };
  30166. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30167. for (var i = 0; i < 10; ++i) {
  30168. this.data[i] += data[i];
  30169. }
  30170. };
  30171. QuadraticMatrix.prototype.add = function (matrix) {
  30172. var m = new QuadraticMatrix();
  30173. for (var i = 0; i < 10; ++i) {
  30174. m.data[i] = this.data[i] + matrix.data[i];
  30175. }
  30176. return m;
  30177. };
  30178. QuadraticMatrix.FromData = function (a, b, c, d) {
  30179. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30180. };
  30181. //returning an array to avoid garbage collection
  30182. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30183. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30184. };
  30185. return QuadraticMatrix;
  30186. })();
  30187. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30188. var Reference = (function () {
  30189. function Reference(vertexId, triangleId) {
  30190. this.vertexId = vertexId;
  30191. this.triangleId = triangleId;
  30192. }
  30193. return Reference;
  30194. })();
  30195. BABYLON.Reference = Reference;
  30196. /**
  30197. * An implementation of the Quadratic Error simplification algorithm.
  30198. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30199. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30200. * @author RaananW
  30201. */
  30202. var QuadraticErrorSimplification = (function () {
  30203. function QuadraticErrorSimplification(_mesh) {
  30204. this._mesh = _mesh;
  30205. this.initialized = false;
  30206. this.syncIterations = 5000;
  30207. this.aggressiveness = 7;
  30208. this.decimationIterations = 100;
  30209. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30210. }
  30211. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30212. var _this = this;
  30213. this.initDecimatedMesh();
  30214. //iterating through the submeshes array, one after the other.
  30215. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30216. _this.initWithMesh(loop.index, function () {
  30217. _this.runDecimation(settings, loop.index, function () {
  30218. loop.executeNext();
  30219. });
  30220. }, settings.optimizeMesh);
  30221. }, function () {
  30222. setTimeout(function () {
  30223. successCallback(_this._reconstructedMesh);
  30224. }, 0);
  30225. });
  30226. };
  30227. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30228. var _this = this;
  30229. var gCount = 0;
  30230. triangle.vertices.forEach(function (vertex) {
  30231. var count = 0;
  30232. var vPos = vertex.position;
  30233. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30234. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30235. ++count;
  30236. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  30237. ++count;
  30238. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  30239. ++count;
  30240. if (count > 1) {
  30241. ++gCount;
  30242. }
  30243. ;
  30244. });
  30245. if (gCount > 1) {
  30246. console.log(triangle, gCount);
  30247. }
  30248. return gCount > 1;
  30249. };
  30250. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30251. var _this = this;
  30252. var targetCount = ~~(this.triangles.length * settings.quality);
  30253. var deletedTriangles = 0;
  30254. var triangleCount = this.triangles.length;
  30255. var iterationFunction = function (iteration, callback) {
  30256. setTimeout(function () {
  30257. if (iteration % 5 === 0) {
  30258. _this.updateMesh(iteration === 0);
  30259. }
  30260. for (var i = 0; i < _this.triangles.length; ++i) {
  30261. _this.triangles[i].isDirty = false;
  30262. }
  30263. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30264. var trianglesIterator = function (i) {
  30265. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30266. var t = _this.triangles[tIdx];
  30267. if (!t)
  30268. return;
  30269. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30270. return;
  30271. }
  30272. for (var j = 0; j < 3; ++j) {
  30273. if (t.error[j] < threshold) {
  30274. var deleted0 = [];
  30275. var deleted1 = [];
  30276. var v0 = t.vertices[j];
  30277. var v1 = t.vertices[(j + 1) % 3];
  30278. if (v0.isBorder !== v1.isBorder)
  30279. continue;
  30280. var p = BABYLON.Vector3.Zero();
  30281. var n = BABYLON.Vector3.Zero();
  30282. var uv = BABYLON.Vector2.Zero();
  30283. var color = new BABYLON.Color4(0, 0, 0, 1);
  30284. _this.calculateError(v0, v1, p, n, uv, color);
  30285. var delTr = [];
  30286. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30287. continue;
  30288. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30289. continue;
  30290. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30291. continue;
  30292. var uniqueArray = [];
  30293. delTr.forEach(function (deletedT) {
  30294. if (uniqueArray.indexOf(deletedT) === -1) {
  30295. deletedT.deletePending = true;
  30296. uniqueArray.push(deletedT);
  30297. }
  30298. });
  30299. if (uniqueArray.length % 2 != 0) {
  30300. continue;
  30301. }
  30302. v0.q = v1.q.add(v0.q);
  30303. v0.updatePosition(p);
  30304. var tStart = _this.references.length;
  30305. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30306. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30307. var tCount = _this.references.length - tStart;
  30308. if (tCount <= v0.triangleCount) {
  30309. if (tCount) {
  30310. for (var c = 0; c < tCount; c++) {
  30311. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30312. }
  30313. }
  30314. }
  30315. else {
  30316. v0.triangleStart = tStart;
  30317. }
  30318. v0.triangleCount = tCount;
  30319. break;
  30320. }
  30321. }
  30322. };
  30323. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  30324. return (triangleCount - deletedTriangles <= targetCount);
  30325. });
  30326. }, 0);
  30327. };
  30328. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30329. if (triangleCount - deletedTriangles <= targetCount)
  30330. loop.breakLoop();
  30331. else {
  30332. iterationFunction(loop.index, function () {
  30333. loop.executeNext();
  30334. });
  30335. }
  30336. }, function () {
  30337. setTimeout(function () {
  30338. //reconstruct this part of the mesh
  30339. _this.reconstructMesh(submeshIndex);
  30340. successCallback();
  30341. }, 0);
  30342. });
  30343. };
  30344. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30345. var _this = this;
  30346. this.vertices = [];
  30347. this.triangles = [];
  30348. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30349. var indices = this._mesh.getIndices();
  30350. var submesh = this._mesh.subMeshes[submeshIndex];
  30351. var findInVertices = function (positionToSearch) {
  30352. if (optimizeMesh) {
  30353. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30354. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30355. return _this.vertices[ii];
  30356. }
  30357. }
  30358. }
  30359. return null;
  30360. };
  30361. var vertexReferences = [];
  30362. var vertexInit = function (i) {
  30363. var offset = i + submesh.verticesStart;
  30364. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30365. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30366. vertex.originalOffsets.push(offset);
  30367. if (vertex.id == _this.vertices.length) {
  30368. _this.vertices.push(vertex);
  30369. }
  30370. vertexReferences.push(vertex.id);
  30371. };
  30372. //var totalVertices = mesh.getTotalVertices();
  30373. var totalVertices = submesh.verticesCount;
  30374. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30375. var indicesInit = function (i) {
  30376. var offset = (submesh.indexStart / 3) + i;
  30377. var pos = (offset * 3);
  30378. var i0 = indices[pos + 0];
  30379. var i1 = indices[pos + 1];
  30380. var i2 = indices[pos + 2];
  30381. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30382. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30383. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30384. var triangle = new DecimationTriangle([v0, v1, v2]);
  30385. triangle.originalOffset = pos;
  30386. _this.triangles.push(triangle);
  30387. };
  30388. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30389. _this.init(callback);
  30390. });
  30391. });
  30392. };
  30393. QuadraticErrorSimplification.prototype.init = function (callback) {
  30394. var _this = this;
  30395. var triangleInit1 = function (i) {
  30396. var t = _this.triangles[i];
  30397. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30398. for (var j = 0; j < 3; j++) {
  30399. 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))));
  30400. }
  30401. };
  30402. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30403. var triangleInit2 = function (i) {
  30404. var t = _this.triangles[i];
  30405. for (var j = 0; j < 3; ++j) {
  30406. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30407. }
  30408. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30409. };
  30410. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30411. _this.initialized = true;
  30412. callback();
  30413. });
  30414. });
  30415. };
  30416. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30417. var newTriangles = [];
  30418. var i;
  30419. for (i = 0; i < this.vertices.length; ++i) {
  30420. this.vertices[i].triangleCount = 0;
  30421. }
  30422. var t;
  30423. var j;
  30424. for (i = 0; i < this.triangles.length; ++i) {
  30425. if (!this.triangles[i].deleted) {
  30426. t = this.triangles[i];
  30427. for (j = 0; j < 3; ++j) {
  30428. t.vertices[j].triangleCount = 1;
  30429. }
  30430. newTriangles.push(t);
  30431. }
  30432. }
  30433. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30434. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30435. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30436. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30437. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30438. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30439. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30440. var vertexCount = 0;
  30441. for (i = 0; i < this.vertices.length; ++i) {
  30442. var vertex = this.vertices[i];
  30443. vertex.id = vertexCount;
  30444. if (vertex.triangleCount) {
  30445. vertex.originalOffsets.forEach(function (originalOffset) {
  30446. newPositionData.push(vertex.position.x);
  30447. newPositionData.push(vertex.position.y);
  30448. newPositionData.push(vertex.position.z);
  30449. newNormalData.push(normalData[originalOffset * 3]);
  30450. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30451. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30452. if (uvs && uvs.length) {
  30453. newUVsData.push(uvs[(originalOffset * 2)]);
  30454. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30455. }
  30456. else if (colorsData && colorsData.length) {
  30457. newColorsData.push(colorsData[(originalOffset * 4)]);
  30458. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30459. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30460. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30461. }
  30462. ++vertexCount;
  30463. });
  30464. }
  30465. }
  30466. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30467. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30468. var submeshesArray = this._reconstructedMesh.subMeshes;
  30469. this._reconstructedMesh.subMeshes = [];
  30470. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30471. var originalIndices = this._mesh.getIndices();
  30472. for (i = 0; i < newTriangles.length; ++i) {
  30473. var t = newTriangles[i];
  30474. //now get the new referencing point for each vertex
  30475. [0, 1, 2].forEach(function (idx) {
  30476. var id = originalIndices[t.originalOffset + idx];
  30477. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30478. if (offset < 0)
  30479. offset = 0;
  30480. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30481. });
  30482. }
  30483. //overwriting the old vertex buffers and indices.
  30484. this._reconstructedMesh.setIndices(newIndicesArray);
  30485. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30486. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30487. if (newUVsData.length > 0)
  30488. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30489. if (newColorsData.length > 0)
  30490. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30491. //create submesh
  30492. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30493. if (submeshIndex > 0) {
  30494. this._reconstructedMesh.subMeshes = [];
  30495. submeshesArray.forEach(function (submesh) {
  30496. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30497. });
  30498. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30499. }
  30500. };
  30501. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30502. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30503. this._reconstructedMesh.material = this._mesh.material;
  30504. this._reconstructedMesh.parent = this._mesh.parent;
  30505. this._reconstructedMesh.isVisible = false;
  30506. };
  30507. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30508. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30509. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30510. if (t.deleted)
  30511. continue;
  30512. var s = this.references[vertex1.triangleStart + i].vertexId;
  30513. var v1 = t.vertices[(s + 1) % 3];
  30514. var v2 = t.vertices[(s + 2) % 3];
  30515. if ((v1 === vertex2 || v2 === vertex2)) {
  30516. deletedArray[i] = true;
  30517. delTr.push(t);
  30518. continue;
  30519. }
  30520. var d1 = v1.position.subtract(point);
  30521. d1 = d1.normalize();
  30522. var d2 = v2.position.subtract(point);
  30523. d2 = d2.normalize();
  30524. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30525. return true;
  30526. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30527. deletedArray[i] = false;
  30528. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30529. return true;
  30530. }
  30531. return false;
  30532. };
  30533. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30534. var newDeleted = deletedTriangles;
  30535. for (var i = 0; i < vertex.triangleCount; ++i) {
  30536. var ref = this.references[vertex.triangleStart + i];
  30537. var t = this.triangles[ref.triangleId];
  30538. if (t.deleted)
  30539. continue;
  30540. if (deletedArray[i] && t.deletePending) {
  30541. t.deleted = true;
  30542. newDeleted++;
  30543. continue;
  30544. }
  30545. t.vertices[ref.vertexId] = origVertex;
  30546. t.isDirty = true;
  30547. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30548. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30549. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30550. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30551. this.references.push(ref);
  30552. }
  30553. return newDeleted;
  30554. };
  30555. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30556. for (var i = 0; i < this.vertices.length; ++i) {
  30557. var vCount = [];
  30558. var vId = [];
  30559. var v = this.vertices[i];
  30560. var j;
  30561. for (j = 0; j < v.triangleCount; ++j) {
  30562. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30563. for (var ii = 0; ii < 3; ii++) {
  30564. var ofs = 0;
  30565. var vv = triangle.vertices[ii];
  30566. while (ofs < vCount.length) {
  30567. if (vId[ofs] === vv.id)
  30568. break;
  30569. ++ofs;
  30570. }
  30571. if (ofs === vCount.length) {
  30572. vCount.push(1);
  30573. vId.push(vv.id);
  30574. }
  30575. else {
  30576. vCount[ofs]++;
  30577. }
  30578. }
  30579. }
  30580. for (j = 0; j < vCount.length; ++j) {
  30581. if (vCount[j] === 1) {
  30582. this.vertices[vId[j]].isBorder = true;
  30583. }
  30584. else {
  30585. this.vertices[vId[j]].isBorder = false;
  30586. }
  30587. }
  30588. }
  30589. };
  30590. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30591. if (identifyBorders === void 0) { identifyBorders = false; }
  30592. var i;
  30593. if (!identifyBorders) {
  30594. var newTrianglesVector = [];
  30595. for (i = 0; i < this.triangles.length; ++i) {
  30596. if (!this.triangles[i].deleted) {
  30597. newTrianglesVector.push(this.triangles[i]);
  30598. }
  30599. }
  30600. this.triangles = newTrianglesVector;
  30601. }
  30602. for (i = 0; i < this.vertices.length; ++i) {
  30603. this.vertices[i].triangleCount = 0;
  30604. this.vertices[i].triangleStart = 0;
  30605. }
  30606. var t;
  30607. var j;
  30608. var v;
  30609. for (i = 0; i < this.triangles.length; ++i) {
  30610. t = this.triangles[i];
  30611. for (j = 0; j < 3; ++j) {
  30612. v = t.vertices[j];
  30613. v.triangleCount++;
  30614. }
  30615. }
  30616. var tStart = 0;
  30617. for (i = 0; i < this.vertices.length; ++i) {
  30618. this.vertices[i].triangleStart = tStart;
  30619. tStart += this.vertices[i].triangleCount;
  30620. this.vertices[i].triangleCount = 0;
  30621. }
  30622. var newReferences = new Array(this.triangles.length * 3);
  30623. for (i = 0; i < this.triangles.length; ++i) {
  30624. t = this.triangles[i];
  30625. for (j = 0; j < 3; ++j) {
  30626. v = t.vertices[j];
  30627. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30628. v.triangleCount++;
  30629. }
  30630. }
  30631. this.references = newReferences;
  30632. if (identifyBorders) {
  30633. this.identifyBorder();
  30634. }
  30635. };
  30636. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30637. var x = point.x;
  30638. var y = point.y;
  30639. var z = point.z;
  30640. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30641. };
  30642. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30643. var q = vertex1.q.add(vertex2.q);
  30644. var border = vertex1.isBorder && vertex2.isBorder;
  30645. var error = 0;
  30646. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30647. if (qDet !== 0 && !border) {
  30648. if (!pointResult) {
  30649. pointResult = BABYLON.Vector3.Zero();
  30650. }
  30651. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30652. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30653. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30654. error = this.vertexError(q, pointResult);
  30655. }
  30656. else {
  30657. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30658. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30659. var error1 = this.vertexError(q, vertex1.position);
  30660. var error2 = this.vertexError(q, vertex2.position);
  30661. var error3 = this.vertexError(q, p3);
  30662. error = Math.min(error1, error2, error3);
  30663. if (error === error1) {
  30664. if (pointResult) {
  30665. pointResult.copyFrom(vertex1.position);
  30666. }
  30667. }
  30668. else if (error === error2) {
  30669. if (pointResult) {
  30670. pointResult.copyFrom(vertex2.position);
  30671. }
  30672. }
  30673. else {
  30674. if (pointResult) {
  30675. pointResult.copyFrom(p3);
  30676. }
  30677. }
  30678. }
  30679. return error;
  30680. };
  30681. return QuadraticErrorSimplification;
  30682. })();
  30683. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30684. })(BABYLON || (BABYLON = {}));
  30685. //# sourceMappingURL=babylon.meshSimplification.js.map
  30686. var BABYLON;
  30687. (function (BABYLON) {
  30688. var Analyser = (function () {
  30689. function Analyser(scene) {
  30690. this.SMOOTHING = 0.75;
  30691. this.FFT_SIZE = 512;
  30692. this.BARGRAPHAMPLITUDE = 256;
  30693. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  30694. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  30695. this._scene = scene;
  30696. this._audioEngine = BABYLON.Engine.audioEngine;
  30697. if (this._audioEngine.canUseWebAudio) {
  30698. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  30699. this._webAudioAnalyser.minDecibels = -140;
  30700. this._webAudioAnalyser.maxDecibels = 0;
  30701. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30702. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30703. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  30704. }
  30705. }
  30706. Analyser.prototype.getFrequencyBinCount = function () {
  30707. if (this._audioEngine.canUseWebAudio) {
  30708. return this._webAudioAnalyser.frequencyBinCount;
  30709. }
  30710. else {
  30711. return 0;
  30712. }
  30713. };
  30714. Analyser.prototype.getByteFrequencyData = function () {
  30715. if (this._audioEngine.canUseWebAudio) {
  30716. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30717. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30718. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  30719. }
  30720. return this._byteFreqs;
  30721. };
  30722. Analyser.prototype.getByteTimeDomainData = function () {
  30723. if (this._audioEngine.canUseWebAudio) {
  30724. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30725. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30726. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  30727. }
  30728. return this._byteTime;
  30729. };
  30730. Analyser.prototype.getFloatFrequencyData = function () {
  30731. if (this._audioEngine.canUseWebAudio) {
  30732. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30733. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30734. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  30735. }
  30736. return this._floatFreqs;
  30737. };
  30738. Analyser.prototype.drawDebugCanvas = function () {
  30739. var _this = this;
  30740. if (this._audioEngine.canUseWebAudio) {
  30741. if (!this._debugCanvas) {
  30742. this._debugCanvas = document.createElement("canvas");
  30743. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  30744. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  30745. this._debugCanvas.style.position = "absolute";
  30746. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  30747. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  30748. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  30749. document.body.appendChild(this._debugCanvas);
  30750. this._registerFunc = function () {
  30751. _this.drawDebugCanvas();
  30752. };
  30753. this._scene.registerBeforeRender(this._registerFunc);
  30754. }
  30755. if (this._registerFunc) {
  30756. var workingArray = this.getByteFrequencyData();
  30757. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  30758. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  30759. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  30760. var value = workingArray[i];
  30761. var percent = value / this.BARGRAPHAMPLITUDE;
  30762. var height = this.DEBUGCANVASSIZE.height * percent;
  30763. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  30764. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  30765. var hue = i / this.getFrequencyBinCount() * 360;
  30766. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  30767. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  30768. }
  30769. }
  30770. }
  30771. };
  30772. Analyser.prototype.stopDebugCanvas = function () {
  30773. if (this._debugCanvas) {
  30774. this._scene.unregisterBeforeRender(this._registerFunc);
  30775. this._registerFunc = null;
  30776. document.body.removeChild(this._debugCanvas);
  30777. this._debugCanvas = null;
  30778. this._debugCanvasContext = null;
  30779. }
  30780. };
  30781. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  30782. if (this._audioEngine.canUseWebAudio) {
  30783. inputAudioNode.connect(this._webAudioAnalyser);
  30784. this._webAudioAnalyser.connect(outputAudioNode);
  30785. }
  30786. };
  30787. Analyser.prototype.dispose = function () {
  30788. if (this._audioEngine.canUseWebAudio) {
  30789. this._webAudioAnalyser.disconnect();
  30790. }
  30791. };
  30792. return Analyser;
  30793. })();
  30794. BABYLON.Analyser = Analyser;
  30795. })(BABYLON || (BABYLON = {}));
  30796. //# sourceMappingURL=babylon.analyser.js.map
  30797. var BABYLON;
  30798. (function (BABYLON) {
  30799. var DepthRenderer = (function () {
  30800. function DepthRenderer(scene, type) {
  30801. var _this = this;
  30802. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  30803. this._viewMatrix = BABYLON.Matrix.Zero();
  30804. this._projectionMatrix = BABYLON.Matrix.Zero();
  30805. this._transformMatrix = BABYLON.Matrix.Zero();
  30806. this._worldViewProjection = BABYLON.Matrix.Zero();
  30807. this._scene = scene;
  30808. var engine = scene.getEngine();
  30809. // Render target
  30810. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  30811. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30812. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30813. this._depthMap.refreshRate = 1;
  30814. this._depthMap.renderParticles = false;
  30815. this._depthMap.renderList = null;
  30816. // set default depth value to 1.0 (far away)
  30817. this._depthMap.onClear = function (engine) {
  30818. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  30819. };
  30820. // Custom render function
  30821. var renderSubMesh = function (subMesh) {
  30822. var mesh = subMesh.getRenderingMesh();
  30823. var scene = _this._scene;
  30824. var engine = scene.getEngine();
  30825. // Culling
  30826. engine.setState(subMesh.getMaterial().backFaceCulling);
  30827. // Managing instances
  30828. var batch = mesh._getInstancesRenderList(subMesh._id);
  30829. if (batch.mustReturn) {
  30830. return;
  30831. }
  30832. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30833. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30834. engine.enableEffect(_this._effect);
  30835. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  30836. var material = subMesh.getMaterial();
  30837. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30838. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  30839. // Alpha test
  30840. if (material && material.needAlphaTesting()) {
  30841. var alphaTexture = material.getAlphaTestTexture();
  30842. _this._effect.setTexture("diffuseSampler", alphaTexture);
  30843. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30844. }
  30845. // Bones
  30846. if (mesh.useBones) {
  30847. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30848. }
  30849. // Draw
  30850. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  30851. }
  30852. };
  30853. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  30854. var index;
  30855. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30856. renderSubMesh(opaqueSubMeshes.data[index]);
  30857. }
  30858. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30859. renderSubMesh(alphaTestSubMeshes.data[index]);
  30860. }
  30861. };
  30862. }
  30863. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  30864. var defines = [];
  30865. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30866. var mesh = subMesh.getMesh();
  30867. var scene = mesh.getScene();
  30868. var material = subMesh.getMaterial();
  30869. // Alpha test
  30870. if (material && material.needAlphaTesting()) {
  30871. defines.push("#define ALPHATEST");
  30872. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30873. attribs.push(BABYLON.VertexBuffer.UVKind);
  30874. defines.push("#define UV1");
  30875. }
  30876. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30877. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30878. defines.push("#define UV2");
  30879. }
  30880. }
  30881. // Bones
  30882. if (mesh.useBones) {
  30883. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30884. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30885. defines.push("#define BONES");
  30886. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30887. }
  30888. // Instances
  30889. if (useInstances) {
  30890. defines.push("#define INSTANCES");
  30891. attribs.push("world0");
  30892. attribs.push("world1");
  30893. attribs.push("world2");
  30894. attribs.push("world3");
  30895. }
  30896. // Get correct effect
  30897. var join = defines.join("\n");
  30898. if (this._cachedDefines !== join) {
  30899. this._cachedDefines = join;
  30900. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  30901. }
  30902. return this._effect.isReady();
  30903. };
  30904. DepthRenderer.prototype.getDepthMap = function () {
  30905. return this._depthMap;
  30906. };
  30907. // Methods
  30908. DepthRenderer.prototype.dispose = function () {
  30909. this._depthMap.dispose();
  30910. };
  30911. return DepthRenderer;
  30912. })();
  30913. BABYLON.DepthRenderer = DepthRenderer;
  30914. })(BABYLON || (BABYLON = {}));
  30915. //# sourceMappingURL=babylon.depthRenderer.js.map
  30916. var __extends = this.__extends || function (d, b) {
  30917. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  30918. function __() { this.constructor = d; }
  30919. __.prototype = b.prototype;
  30920. d.prototype = new __();
  30921. };
  30922. var BABYLON;
  30923. (function (BABYLON) {
  30924. var SSAORenderingPipeline = (function (_super) {
  30925. __extends(SSAORenderingPipeline, _super);
  30926. /**
  30927. * @constructor
  30928. * @param {string} name - The rendering pipeline name
  30929. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  30930. * @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 }
  30931. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  30932. */
  30933. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  30934. var _this = this;
  30935. _super.call(this, scene.getEngine(), name);
  30936. // Members
  30937. /**
  30938. * The PassPostProcess id in the pipeline that contains the original scene color
  30939. * @type {string}
  30940. */
  30941. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  30942. /**
  30943. * The SSAO PostProcess id in the pipeline
  30944. * @type {string}
  30945. */
  30946. this.SSAORenderEffect = "SSAORenderEffect";
  30947. /**
  30948. * The horizontal blur PostProcess id in the pipeline
  30949. * @type {string}
  30950. */
  30951. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  30952. /**
  30953. * The vertical blur PostProcess id in the pipeline
  30954. * @type {string}
  30955. */
  30956. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  30957. /**
  30958. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  30959. * @type {string}
  30960. */
  30961. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  30962. /**
  30963. * The output strength of the SSAO post-process. Default value is 1.0.
  30964. * @type {number}
  30965. */
  30966. this.totalStrength = 1.0;
  30967. /**
  30968. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  30969. * @type {number}
  30970. */
  30971. this.radius = 0.0002;
  30972. /**
  30973. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  30974. * Must not be equal to fallOff and superior to fallOff.
  30975. * Default value is 0.0075
  30976. * @type {number}
  30977. */
  30978. this.area = 0.0075;
  30979. /**
  30980. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  30981. * Must not be equal to area and inferior to area.
  30982. * Default value is 0.0002
  30983. * @type {number}
  30984. */
  30985. this.fallOff = 0.0002;
  30986. this._firstUpdate = true;
  30987. this._scene = scene;
  30988. // Set up assets
  30989. this._createRandomTexture();
  30990. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  30991. var ssaoRatio = ratio.ssaoRatio || ratio;
  30992. var combineRatio = ratio.combineRatio || ratio;
  30993. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30994. this._createSSAOPostProcess(ssaoRatio);
  30995. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30996. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  30997. this._createSSAOCombinePostProcess(combineRatio);
  30998. // Set up pipeline
  30999. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  31000. return _this._originalColorPostProcess;
  31001. }, true));
  31002. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  31003. return _this._ssaoPostProcess;
  31004. }, true));
  31005. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  31006. return _this._blurHPostProcess;
  31007. }, true));
  31008. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  31009. return _this._blurVPostProcess;
  31010. }, true));
  31011. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  31012. return _this._ssaoCombinePostProcess;
  31013. }, true));
  31014. // Finish
  31015. scene.postProcessRenderPipelineManager.addPipeline(this);
  31016. if (cameras)
  31017. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31018. }
  31019. // Public Methods
  31020. /**
  31021. * Returns the horizontal blur PostProcess
  31022. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  31023. */
  31024. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  31025. return this._blurHPostProcess;
  31026. };
  31027. /**
  31028. * Returns the vertical blur PostProcess
  31029. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  31030. */
  31031. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  31032. return this._blurVPostProcess;
  31033. };
  31034. /**
  31035. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  31036. */
  31037. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31038. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31039. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31040. this._originalColorPostProcess = undefined;
  31041. this._ssaoPostProcess = undefined;
  31042. this._blurHPostProcess = undefined;
  31043. this._blurVPostProcess = undefined;
  31044. this._ssaoCombinePostProcess = undefined;
  31045. this._randomTexture.dispose();
  31046. if (disableDepthRender)
  31047. this._scene.disableDepthRenderer();
  31048. };
  31049. // Private Methods
  31050. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  31051. var _this = this;
  31052. var sampleSphere = [
  31053. 0.5381,
  31054. 0.1856,
  31055. -0.4319,
  31056. 0.1379,
  31057. 0.2486,
  31058. 0.4430,
  31059. 0.3371,
  31060. 0.5679,
  31061. -0.0057,
  31062. -0.6999,
  31063. -0.0451,
  31064. -0.0019,
  31065. 0.0689,
  31066. -0.1598,
  31067. -0.8547,
  31068. 0.0560,
  31069. 0.0069,
  31070. -0.1843,
  31071. -0.0146,
  31072. 0.1402,
  31073. 0.0762,
  31074. 0.0100,
  31075. -0.1924,
  31076. -0.0344,
  31077. -0.3577,
  31078. -0.5301,
  31079. -0.4358,
  31080. -0.3169,
  31081. 0.1063,
  31082. 0.0158,
  31083. 0.0103,
  31084. -0.5869,
  31085. 0.0046,
  31086. -0.0897,
  31087. -0.4940,
  31088. 0.3287,
  31089. 0.7119,
  31090. -0.0154,
  31091. -0.0918,
  31092. -0.0533,
  31093. 0.0596,
  31094. -0.5411,
  31095. 0.0352,
  31096. -0.0631,
  31097. 0.5460,
  31098. -0.4776,
  31099. 0.2847,
  31100. -0.0271
  31101. ];
  31102. var samplesFactor = 1.0 / 16.0;
  31103. 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);
  31104. this._ssaoPostProcess.onApply = function (effect) {
  31105. if (_this._firstUpdate) {
  31106. effect.setArray3("sampleSphere", sampleSphere);
  31107. effect.setFloat("samplesFactor", samplesFactor);
  31108. effect.setFloat("randTextureTiles", 4.0 / ratio);
  31109. _this._firstUpdate = false;
  31110. }
  31111. effect.setFloat("totalStrength", _this.totalStrength);
  31112. effect.setFloat("radius", _this.radius);
  31113. effect.setFloat("area", _this.area);
  31114. effect.setFloat("fallOff", _this.fallOff);
  31115. effect.setTexture("textureSampler", _this._depthTexture);
  31116. effect.setTexture("randomSampler", _this._randomTexture);
  31117. };
  31118. };
  31119. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  31120. var _this = this;
  31121. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31122. this._ssaoCombinePostProcess.onApply = function (effect) {
  31123. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  31124. };
  31125. };
  31126. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  31127. var size = 512;
  31128. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31129. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31130. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31131. var context = this._randomTexture.getContext();
  31132. var rand = function (min, max) {
  31133. return Math.random() * (max - min) + min;
  31134. };
  31135. for (var x = 0; x < size; x++) {
  31136. for (var y = 0; y < size; y++) {
  31137. var randVector = BABYLON.Vector3.Zero();
  31138. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  31139. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  31140. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  31141. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  31142. context.fillRect(x, y, 1, 1);
  31143. }
  31144. }
  31145. this._randomTexture.update(false);
  31146. };
  31147. return SSAORenderingPipeline;
  31148. })(BABYLON.PostProcessRenderPipeline);
  31149. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  31150. })(BABYLON || (BABYLON = {}));
  31151. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  31152. var __extends = this.__extends || function (d, b) {
  31153. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31154. function __() { this.constructor = d; }
  31155. __.prototype = b.prototype;
  31156. d.prototype = new __();
  31157. };
  31158. var BABYLON;
  31159. (function (BABYLON) {
  31160. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  31161. var VolumetricLightScatteringPostProcess = (function (_super) {
  31162. __extends(VolumetricLightScatteringPostProcess, _super);
  31163. /**
  31164. * @constructor
  31165. * @param {string} name - The post-process name
  31166. * @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)
  31167. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  31168. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  31169. * @param {number} samples - The post-process quality, default 100
  31170. * @param {number} samplingMode - The post-process filtering mode
  31171. * @param {BABYLON.Engine} engine - The babylon engine
  31172. * @param {boolean} reusable - If the post-process is reusable
  31173. */
  31174. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  31175. var _this = this;
  31176. if (samples === void 0) { samples = 100; }
  31177. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31178. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  31179. this._screenCoordinates = BABYLON.Vector2.Zero();
  31180. /**
  31181. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  31182. * @type {boolean}
  31183. */
  31184. this.useCustomMeshPosition = false;
  31185. /**
  31186. * If the post-process should inverse the light scattering direction
  31187. * @type {boolean}
  31188. */
  31189. this.invert = true;
  31190. /**
  31191. * Array containing the excluded meshes not rendered in the internal pass
  31192. */
  31193. this.excludedMeshes = new Array();
  31194. this.exposure = 0.3;
  31195. this.decay = 0.96815;
  31196. this.weight = 0.58767;
  31197. this.density = 0.926;
  31198. var scene = camera.getScene();
  31199. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  31200. // Configure mesh
  31201. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  31202. // Configure
  31203. this._createPass(scene, ratio.passRatio || ratio);
  31204. this.onApply = function (effect) {
  31205. _this._updateMeshScreenCoordinates(scene);
  31206. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  31207. effect.setFloat("exposure", _this.exposure);
  31208. effect.setFloat("decay", _this.decay);
  31209. effect.setFloat("weight", _this.weight);
  31210. effect.setFloat("density", _this.density);
  31211. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  31212. };
  31213. }
  31214. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  31215. var mesh = subMesh.getMesh();
  31216. var defines = [];
  31217. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31218. var material = subMesh.getMaterial();
  31219. var needUV = false;
  31220. // Render this.mesh as default
  31221. if (mesh === this.mesh) {
  31222. defines.push("#define BASIC_RENDER");
  31223. defines.push("#define NEED_UV");
  31224. needUV = true;
  31225. }
  31226. // Alpha test
  31227. if (material) {
  31228. if (material.needAlphaTesting() || mesh === this.mesh)
  31229. defines.push("#define ALPHATEST");
  31230. if (material.opacityTexture !== undefined) {
  31231. defines.push("#define OPACITY");
  31232. if (material.opacityTexture.getAlphaFromRGB)
  31233. defines.push("#define OPACITYRGB");
  31234. if (!needUV)
  31235. defines.push("#define NEED_UV");
  31236. }
  31237. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31238. attribs.push(BABYLON.VertexBuffer.UVKind);
  31239. defines.push("#define UV1");
  31240. }
  31241. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31242. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31243. defines.push("#define UV2");
  31244. }
  31245. }
  31246. // Bones
  31247. if (mesh.useBones) {
  31248. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31249. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31250. defines.push("#define BONES");
  31251. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31252. }
  31253. // Instances
  31254. if (useInstances) {
  31255. defines.push("#define INSTANCES");
  31256. attribs.push("world0");
  31257. attribs.push("world1");
  31258. attribs.push("world2");
  31259. attribs.push("world3");
  31260. }
  31261. // Get correct effect
  31262. var join = defines.join("\n");
  31263. if (this._cachedDefines !== join) {
  31264. this._cachedDefines = join;
  31265. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  31266. }
  31267. return this._volumetricLightScatteringPass.isReady();
  31268. };
  31269. /**
  31270. * Sets the new light position for light scattering effect
  31271. * @param {BABYLON.Vector3} The new custom light position
  31272. */
  31273. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  31274. this._customMeshPosition = position;
  31275. };
  31276. /**
  31277. * Returns the light position for light scattering effect
  31278. * @return {BABYLON.Vector3} The custom light position
  31279. */
  31280. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  31281. return this._customMeshPosition;
  31282. };
  31283. /**
  31284. * Disposes the internal assets and detaches the post-process from the camera
  31285. */
  31286. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  31287. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  31288. if (rttIndex !== -1) {
  31289. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  31290. }
  31291. this._volumetricLightScatteringRTT.dispose();
  31292. _super.prototype.dispose.call(this, camera);
  31293. };
  31294. /**
  31295. * Returns the render target texture used by the post-process
  31296. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  31297. */
  31298. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  31299. return this._volumetricLightScatteringRTT;
  31300. };
  31301. // Private methods
  31302. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31303. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31304. return true;
  31305. }
  31306. return false;
  31307. };
  31308. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31309. var _this = this;
  31310. var engine = scene.getEngine();
  31311. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31312. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31313. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31314. this._volumetricLightScatteringRTT.renderList = null;
  31315. this._volumetricLightScatteringRTT.renderParticles = false;
  31316. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31317. // Custom render function for submeshes
  31318. var renderSubMesh = function (subMesh) {
  31319. var mesh = subMesh.getRenderingMesh();
  31320. if (_this._meshExcluded(mesh)) {
  31321. return;
  31322. }
  31323. var scene = mesh.getScene();
  31324. var engine = scene.getEngine();
  31325. // Culling
  31326. engine.setState(subMesh.getMaterial().backFaceCulling);
  31327. // Managing instances
  31328. var batch = mesh._getInstancesRenderList(subMesh._id);
  31329. if (batch.mustReturn) {
  31330. return;
  31331. }
  31332. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31333. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31334. engine.enableEffect(_this._volumetricLightScatteringPass);
  31335. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31336. var material = subMesh.getMaterial();
  31337. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31338. // Alpha test
  31339. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31340. var alphaTexture = material.getAlphaTestTexture();
  31341. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31342. if (alphaTexture) {
  31343. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31344. }
  31345. if (material.opacityTexture !== undefined) {
  31346. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31347. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31348. }
  31349. }
  31350. // Bones
  31351. if (mesh.useBones) {
  31352. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31353. }
  31354. // Draw
  31355. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31356. }
  31357. };
  31358. // Render target texture callbacks
  31359. var savedSceneClearColor;
  31360. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31361. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31362. savedSceneClearColor = scene.clearColor;
  31363. scene.clearColor = sceneClearColor;
  31364. };
  31365. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31366. scene.clearColor = savedSceneClearColor;
  31367. };
  31368. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31369. var engine = scene.getEngine();
  31370. var index;
  31371. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31372. renderSubMesh(opaqueSubMeshes.data[index]);
  31373. }
  31374. engine.setAlphaTesting(true);
  31375. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31376. renderSubMesh(alphaTestSubMeshes.data[index]);
  31377. }
  31378. engine.setAlphaTesting(false);
  31379. if (transparentSubMeshes.length) {
  31380. for (index = 0; index < transparentSubMeshes.length; index++) {
  31381. var submesh = transparentSubMeshes.data[index];
  31382. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31383. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31384. }
  31385. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31386. sortedArray.sort(function (a, b) {
  31387. // Alpha index first
  31388. if (a._alphaIndex > b._alphaIndex) {
  31389. return 1;
  31390. }
  31391. if (a._alphaIndex < b._alphaIndex) {
  31392. return -1;
  31393. }
  31394. // Then distance to camera
  31395. if (a._distanceToCamera < b._distanceToCamera) {
  31396. return 1;
  31397. }
  31398. if (a._distanceToCamera > b._distanceToCamera) {
  31399. return -1;
  31400. }
  31401. return 0;
  31402. });
  31403. // Render sub meshes
  31404. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31405. for (index = 0; index < sortedArray.length; index++) {
  31406. renderSubMesh(sortedArray[index]);
  31407. }
  31408. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31409. }
  31410. };
  31411. };
  31412. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31413. var transform = scene.getTransformMatrix();
  31414. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31415. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31416. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31417. if (this.invert)
  31418. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31419. };
  31420. // Static methods
  31421. /**
  31422. * Creates a default mesh for the Volumeric Light Scattering post-process
  31423. * @param {string} The mesh name
  31424. * @param {BABYLON.Scene} The scene where to create the mesh
  31425. * @return {BABYLON.Mesh} the default mesh
  31426. */
  31427. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31428. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31429. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31430. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31431. return mesh;
  31432. };
  31433. return VolumetricLightScatteringPostProcess;
  31434. })(BABYLON.PostProcess);
  31435. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31436. })(BABYLON || (BABYLON = {}));
  31437. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31438. var __extends = this.__extends || function (d, b) {
  31439. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31440. function __() { this.constructor = d; }
  31441. __.prototype = b.prototype;
  31442. d.prototype = new __();
  31443. };
  31444. var BABYLON;
  31445. (function (BABYLON) {
  31446. var LensRenderingPipeline = (function (_super) {
  31447. __extends(LensRenderingPipeline, _super);
  31448. /**
  31449. * @constructor
  31450. *
  31451. * Effect parameters are as follow:
  31452. * {
  31453. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31454. * edge_blur: number; // from 0 to x (1 for realism)
  31455. * distortion: number; // from 0 to x (1 for realism)
  31456. * grain_amount: number; // from 0 to 1
  31457. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31458. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  31459. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31460. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31461. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  31462. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  31463. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31464. * }
  31465. * Note: if an effect parameter is unset, effect is disabled
  31466. *
  31467. * @param {string} name - The rendering pipeline name
  31468. * @param {object} parameters - An object containing all parameters (see above)
  31469. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31470. * @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)
  31471. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31472. */
  31473. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31474. var _this = this;
  31475. if (ratio === void 0) { ratio = 1.0; }
  31476. _super.call(this, scene.getEngine(), name);
  31477. // Lens effects can be of the following:
  31478. // - chromatic aberration (slight shift of RGB colors)
  31479. // - blur on the edge of the lens
  31480. // - lens distortion
  31481. // - depth-of-field blur & highlights enhancing
  31482. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31483. // - grain effect (noise or custom texture)
  31484. // Two additional texture samplers are needed:
  31485. // - depth map (for depth-of-field)
  31486. // - grain texture
  31487. /**
  31488. * The chromatic aberration PostProcess id in the pipeline
  31489. * @type {string}
  31490. */
  31491. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31492. /**
  31493. * The highlights enhancing PostProcess id in the pipeline
  31494. * @type {string}
  31495. */
  31496. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31497. /**
  31498. * The depth-of-field PostProcess id in the pipeline
  31499. * @type {string}
  31500. */
  31501. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31502. this._scene = scene;
  31503. // Fetch texture samplers
  31504. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31505. if (parameters.grain_texture) {
  31506. this._grainTexture = parameters.grain_texture;
  31507. }
  31508. else {
  31509. this._createGrainTexture();
  31510. }
  31511. // save parameters
  31512. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31513. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31514. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31515. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31516. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31517. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31518. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  31519. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31520. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31521. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31522. // Create effects
  31523. this._createChromaticAberrationPostProcess(ratio);
  31524. this._createHighlightsPostProcess(ratio);
  31525. this._createDepthOfFieldPostProcess(ratio);
  31526. // Set up pipeline
  31527. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  31528. return _this._chromaticAberrationPostProcess;
  31529. }, true));
  31530. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  31531. return _this._highlightsPostProcess;
  31532. }, true));
  31533. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  31534. return _this._depthOfFieldPostProcess;
  31535. }, true));
  31536. if (this._highlightsGain == -1) {
  31537. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31538. }
  31539. // Finish
  31540. scene.postProcessRenderPipelineManager.addPipeline(this);
  31541. if (cameras) {
  31542. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31543. }
  31544. }
  31545. // public methods (self explanatory)
  31546. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  31547. this._edgeBlur = amount;
  31548. };
  31549. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  31550. this._edgeBlur = 0;
  31551. };
  31552. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  31553. this._grainAmount = amount;
  31554. };
  31555. LensRenderingPipeline.prototype.disableGrain = function () {
  31556. this._grainAmount = 0;
  31557. };
  31558. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  31559. this._chromaticAberration = amount;
  31560. };
  31561. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  31562. this._chromaticAberration = 0;
  31563. };
  31564. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  31565. this._distortion = amount;
  31566. };
  31567. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  31568. this._distortion = 0;
  31569. };
  31570. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  31571. this._dofDepth = amount;
  31572. };
  31573. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  31574. this._dofDepth = -1;
  31575. };
  31576. LensRenderingPipeline.prototype.setAperture = function (amount) {
  31577. this._dofAperture = amount;
  31578. };
  31579. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  31580. this._dofPentagon = true;
  31581. };
  31582. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  31583. this._dofPentagon = false;
  31584. };
  31585. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  31586. this._blurNoise = true;
  31587. };
  31588. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  31589. this._blurNoise = false;
  31590. };
  31591. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31592. this._highlightsGain = amount;
  31593. };
  31594. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31595. if (this._highlightsGain == -1) {
  31596. this._highlightsGain = 1.0;
  31597. }
  31598. this._highlightsThreshold = amount;
  31599. };
  31600. LensRenderingPipeline.prototype.disableHighlights = function () {
  31601. this._highlightsGain = -1;
  31602. };
  31603. /**
  31604. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31605. */
  31606. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31607. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31608. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31609. this._chromaticAberrationPostProcess = undefined;
  31610. this._highlightsPostProcess = undefined;
  31611. this._depthOfFieldPostProcess = undefined;
  31612. this._grainTexture.dispose();
  31613. if (disableDepthRender)
  31614. this._scene.disableDepthRenderer();
  31615. };
  31616. // colors shifting and distortion
  31617. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31618. var _this = this;
  31619. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31620. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31621. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31622. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31623. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31624. };
  31625. };
  31626. // highlights enhancing
  31627. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31628. var _this = this;
  31629. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31630. this._highlightsPostProcess.onApply = function (effect) {
  31631. effect.setFloat('gain', _this._highlightsGain);
  31632. effect.setFloat('threshold', _this._highlightsThreshold);
  31633. effect.setBool('pentagon', _this._dofPentagon);
  31634. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31635. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31636. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31637. };
  31638. };
  31639. // colors shifting and distortion
  31640. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31641. var _this = this;
  31642. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31643. "focus_depth",
  31644. "aperture",
  31645. "pentagon",
  31646. "maxZ",
  31647. "edge_blur",
  31648. "chromatic_aberration",
  31649. "distortion",
  31650. "blur_noise",
  31651. "grain_amount",
  31652. "screen_width",
  31653. "screen_height",
  31654. "highlights"
  31655. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31656. this._depthOfFieldPostProcess.onApply = function (effect) {
  31657. effect.setBool('blur_noise', _this._blurNoise);
  31658. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  31659. effect.setFloat('grain_amount', _this._grainAmount);
  31660. effect.setTexture("depthSampler", _this._depthTexture);
  31661. effect.setTexture("grainSampler", _this._grainTexture);
  31662. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31663. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31664. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31665. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31666. effect.setFloat('distortion', _this._distortion);
  31667. effect.setFloat('focus_depth', _this._dofDepth);
  31668. effect.setFloat('aperture', _this._dofAperture);
  31669. effect.setFloat('edge_blur', _this._edgeBlur);
  31670. effect.setBool('highlights', (_this._highlightsGain != -1));
  31671. };
  31672. };
  31673. // creates a black and white random noise texture, 512x512
  31674. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31675. var size = 512;
  31676. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31677. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31678. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31679. var context = this._grainTexture.getContext();
  31680. var rand = function (min, max) {
  31681. return Math.random() * (max - min) + min;
  31682. };
  31683. var value;
  31684. for (var x = 0; x < size; x++) {
  31685. for (var y = 0; y < size; y++) {
  31686. value = Math.floor(rand(0.42, 0.58) * 255);
  31687. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31688. context.fillRect(x, y, 1, 1);
  31689. }
  31690. }
  31691. this._grainTexture.update(false);
  31692. };
  31693. return LensRenderingPipeline;
  31694. })(BABYLON.PostProcessRenderPipeline);
  31695. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31696. })(BABYLON || (BABYLON = {}));
  31697. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31698. //
  31699. // This post-process allows the modification of rendered colors by using
  31700. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31701. //
  31702. // The object needs to be provided an url to a texture containing the color
  31703. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31704. // Use an image editing software to tweak the LUT to match your needs.
  31705. //
  31706. // For an example of a color LUT, see here:
  31707. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31708. // For explanations on color grading, see here:
  31709. // http://udn.epicgames.com/Three/ColorGrading.html
  31710. //
  31711. var __extends = this.__extends || function (d, b) {
  31712. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  31713. function __() { this.constructor = d; }
  31714. __.prototype = b.prototype;
  31715. d.prototype = new __();
  31716. };
  31717. var BABYLON;
  31718. (function (BABYLON) {
  31719. var ColorCorrectionPostProcess = (function (_super) {
  31720. __extends(ColorCorrectionPostProcess, _super);
  31721. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31722. var _this = this;
  31723. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31724. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31725. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31726. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31727. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31728. this.onApply = function (effect) {
  31729. effect.setTexture("colorTable", _this._colorTableTexture);
  31730. };
  31731. }
  31732. return ColorCorrectionPostProcess;
  31733. })(BABYLON.PostProcess);
  31734. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31735. })(BABYLON || (BABYLON = {}));
  31736. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31737. 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}"};
  31738. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var i=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o}();o.CollisionCache=i;var e=function(){function i(i,e,r){this.collider=i,this._collisionCache=e,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return i.prototype.collideWithWorld=function(o,i,e,r){var t=.01;if(this.collider.retry>=e)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,i,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&this.collider._getResponse(o,i),i.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,i,e,r))):void o.addToRef(i,this.finalPosition)},i.prototype.checkCollision=function(i){if(this.collider._canDoCollision(o.Vector3.FromArray(i.sphereCenter),i.sphereRadius,o.Vector3.FromArray(i.boxMinimum),o.Vector3.FromArray(i.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var e=o.Matrix.FromArray(i.worldMatrixFromCache);e.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,i)}},i.prototype.processCollisionsForSubMeshes=function(o,i){var e,r;if(r=i.subMeshes,e=r.length,!i.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(i.geometryId);if(!t)return void console.log(\"couldn't find geometry\",i.geometryId);for(var s=0;e>s;s++){var l=r[s];e>1&&!this.checkSubmeshCollision(l)||this.collideForSubMesh(l,o,t)}},i.prototype.collideForSubMesh=function(i,e,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!i._lastColliderWorldVertices||!i._lastColliderTransformMatrix.equals(e)){i._lastColliderTransformMatrix=e.clone(),i._lastColliderWorldVertices=[],i._trianglePlanes=[];for(var n=i.verticesStart,a=i.verticesStart+i.verticesCount,t=n;a>t;t++)i._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],e))}this.collider._collide(i._trianglePlanes,i._lastColliderWorldVertices,r.indices,i.indexStart,i.indexStart+i.indexCount,i.verticesStart,i.hasMaterial)},i.prototype.checkSubmeshCollision=function(i){return this.collider._canDoCollision(o.Vector3.FromArray(i.sphereCenter),i.sphereRadius,o.Vector3.FromArray(i.boxMinimum),o.Vector3.FromArray(i.boxMaximum))},i}();o.CollideWorker=e;var r=function(){function r(){}return r.prototype.onInit=function(o){this._collisionCache=new i;var e={error:0,taskType:0};postMessage(e,void 0)},r.prototype.onUpdate=function(o){for(var i in o.updatedGeometries)o.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(o.updatedGeometries[i]);for(var e in o.updatedMeshes)o.updatedMeshes.hasOwnProperty(e)&&this._collisionCache.addMesh(o.updatedMeshes[e]);var r={error:0,taskType:1};postMessage(r,void 0)},r.prototype.onCollision=function(i){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(i.collider.radius);var s=new e(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(i.collider.position),o.Vector3.FromArray(i.collider.velocity),i.maximumRetry,i.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:i.collisionId,newPosition:r.asArray()},n={error:0,taskType:2,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(o){var i=o.data;switch(i.taskType){case 0:t.onInit(i.payload);break;case 2:t.onCollision(i.payload);break;case 1:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var o=(e.WorkerReplyType,function(){function o(){var i=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){i._addUpdateMeshesList[e.uniqueId]=o.SerializeMesh(e)},this.onGeometryUpdated=function(e){i._addUpdateGeometriesList[e.id]=o.SerializeGeometry(e)},this._afterRender=function(){if(i._init&&!(0==i._toRemoveGeometryArray.length&&0==i._toRemoveMeshesArray.length&&0==Object.keys(i._addUpdateGeometriesList).length&&0==Object.keys(i._addUpdateMeshesList).length||i._runningUpdated>4)){++i._runningUpdated;var e={updatedMeshes:i._addUpdateMeshesList,updatedGeometries:i._addUpdateGeometriesList,removedGeometries:i._toRemoveGeometryArray,removedMeshes:i._toRemoveMeshesArray},o={payload:e,taskType:1},t=[];for(var r in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(r)&&(t.push(o.payload.updatedGeometries[r].indices.buffer),t.push(o.payload.updatedGeometries[r].normals.buffer),t.push(o.payload.updatedGeometries[r].positions.buffer));i._worker.postMessage(o,t),i._addUpdateMeshesList={},i._addUpdateGeometriesList={},i._toRemoveGeometryArray=[],i._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(o){var t=o.data;if(0!=t.error)return void e.Tools.Warn(\"error returned from worker!\");switch(t.taskType){case 0:i._init=!0,i._scene.meshes.forEach(function(e){i.onMeshAdded(e)}),i._scene.getGeometries().forEach(function(e){i.onGeometryAdded(e)});break;case 1:i._runningUpdated--;break;case 2:i._runningCollisionTask=!1;var r=t.payload;if(!i._collisionsCallbackArray[r.collisionId])return;i._collisionsCallbackArray[r.collisionId](r.collisionId,e.Vector3.FromArray(r.newPosition),i._scene.getMeshByUniqueID(r.collidedMeshUniqueId)),i._collisionsCallbackArray[r.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){if(this._init&&!this._collisionsCallbackArray[n]&&!this._collisionsCallbackArray[n+1e5]){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),this._collisionsCallbackArray[n]=s;var a={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:i.radius.asArray()},collisionId:n,excludedMeshUniqueId:r?r.uniqueId:null,maximumRetry:t},d={payload:a,taskType:2};this._worker.postMessage(d)}},o.prototype.init=function(o){this._scene=o,this._scene.registerAfterRender(this._afterRender);var i=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(i),this._worker.onmessage=this._onMessageFromWorker;var t={payload:{},taskType:0};this._worker.postMessage(t)},o.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},o.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},o.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},o.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},o.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},o.SerializeMesh=function(e){var o=[];e.subMeshes&&(o=e.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var i=e.geometry?e.geometry.id:null;return{uniqueId:e.uniqueId,id:e.id,name:e.name,geometryId:i,sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:e.worldMatrixFromCache.asArray(),subMeshes:o,checkCollisions:e.checkCollisions}},o.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},o}());e.CollisionCoordinatorWorker=o;var i=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=i}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function t(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},t.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},t.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b)},t.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},t.prototype.clone=function(){return new t(this.r,this.g,this.b)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},t.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2])},t.FromInts=function(i,o,n){return new t(i/255,o/255,n/255)},t.Lerp=function(i,o,n){var r=i.r+(o.r-i.r)*n,s=i.g+(o.g-i.g)*n,e=i.b+(o.b-i.b)*n;return new t(r,s,e)},t.Red=function(){return new t(1,0,0)},t.Green=function(){return new t(0,1,0)},t.Blue=function(){return new t(0,0,1)},t.Black=function(){return new t(0,0,0)},t.White=function(){return new t(1,1,1)},t.Purple=function(){return new t(.5,0,.5)},t.Magenta=function(){return new t(1,0,1)},t.Yellow=function(){return new t(1,1,0)},t.Gray=function(){return new t(.5,.5,.5)},t}();t.Color3=i;var o=function(){function t(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.Lerp=function(i,o,n){var r=new t(0,0,0,0);return t.LerpToRef(i,o,n,r),r},t.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.FromInts=function(i,o,n,r){return new t(i/255,o/255,n/255,r/255)},t}();t.Color4=o;var n=function(){function 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,function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,o){var n=o.subtract(i),r=Math.atan2(n.y,n.x);return new t(r)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}());t.Angle=y;var c=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new n((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=y.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=y.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=y.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?0:1,this.angle=y.FromDegrees(0===this.orientation?h-l:l-h)}return t}();t.Arc2=c;var p=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new r(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=p;var z=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new n(i,o),s=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,r,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new n(i,o),u=new n(r,s),l=new c(a,h,u),m=l.angle.radians()/e;0===l.orientation&&(m*=-1);for(var f=l.startAngle.radians()+m,x=0;e>x;x++){var y=Math.cos(f)*l.radius+l.centerPoint.x,p=Math.sin(f)*l.radius+l.centerPoint.y;this.addLineTo(y,p),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=z;var M=function(){function t(t,i){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var o=0;o<t.length;o++)this._curve[o]=t[o].clone();this._compute(i)}return t.prototype.getCurve=function(){return this._curve},t.prototype.getTangents=function(){return this._tangents},t.prototype.getNormals=function(){return this._normals},t.prototype.getBinormals=function(){return this._binormals},t.prototype.getDistances=function(){return this._distances},t.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},t.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._tangents[i-1].normalize();var o=this._tangents[0],n=this._normalVector(this._curve[0],o,t);this._normals[0]=n,this._normals[0].normalize(),this._binormals[0]=r.Cross(o,this._normals[0]),this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u,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=M;var w=function(){function i(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return i.CreateQuadraticBezier=function(t,o,n,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,n){var r=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*n;return r},h=0;s>=h;h++)e.push(new r(a(h/s,t.x,o.x,n.x),a(h/s,t.y,o.y,n.y),a(h/s,t.z,o.z,n.z)));return new i(e)},i.CreateCubicBezier=function(t,o,n,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,n,r){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*n+t*t*t*r;return s},u=0;e>=u;u++)a.push(new r(h(u/e,t.x,o.x,n.x,s.x),h(u/e,t.y,o.y,n.y,s.y),h(u/e,t.z,o.z,n.z,s.z)));return new i(a)},i.CreateHermiteSpline=function(o,n,r,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(t.Vector3.Hermite(o,n,r,s,u*h));return new i(a)},i.prototype.getPoints=function(){return this._points},i.prototype.length=function(){return this._length},i.prototype[\"continue\"]=function(t){for(var o=this._points[this._points.length-1],n=this._points.slice(),r=t.getPoints(),s=1;s<r.length;s++)n.push(r[s].subtract(r[0]).add(o));var e=new i(n);return e},i.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},i}();t.Curve3=w;var I=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=I;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 D=a.prototype.multiplyToArray,S=a.prototype.invertToRef,v=a.LookAtLHToRef,g=r.TransformCoordinatesToRef,T=r.TransformCoordinatesFromFloatsToRef,R=function(){function i(){}return Object.defineProperty(i,\"IsEnabled\",{get:function(){return i._isEnabled},enumerable:!0,configurable:!0}),i.DisableSIMD=function(){a.prototype.multiplyToArray=D,a.prototype.invertToRef=S,a.LookAtLHToRef=v,r.TransformCoordinatesToRef=g,r.TransformCoordinatesFromFloatsToRef=T,i._isEnabled=!1},i.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,r.TransformCoordinatesToRef=r.TransformCoordinatesToRefSIMD,r.TransformCoordinatesFromFloatsToRef=r.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(t.Vector3.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(t.Vector3.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(t.Vector3.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),i._isEnabled=!0)},i._isEnabled=!1,i}();t.SIMDHelper=R,void 0!==window.SIMD&&window.SIMD.float32x4&&window.SIMD.float32x4.swizzle&&R.EnableSIMD()}(BABYLON||(BABYLON={}));";