babylon.2.0-beta.debug.js 1.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (typeof r === "undefined") { r = 0; }
  11. if (typeof g === "undefined") { g = 0; }
  12. if (typeof b === "undefined") { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. };
  29. Color3.prototype.toColor4 = function (alpha) {
  30. if (typeof alpha === "undefined") { alpha = 1; }
  31. return new Color4(this.r, this.g, this.b, alpha);
  32. };
  33. Color3.prototype.asArray = function () {
  34. var result = [];
  35. this.toArray(result, 0);
  36. return result;
  37. };
  38. Color3.prototype.toLuminance = function () {
  39. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  40. };
  41. Color3.prototype.multiply = function (otherColor) {
  42. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  43. };
  44. Color3.prototype.multiplyToRef = function (otherColor, result) {
  45. result.r = this.r * otherColor.r;
  46. result.g = this.g * otherColor.g;
  47. result.b = this.b * otherColor.b;
  48. };
  49. Color3.prototype.equals = function (otherColor) {
  50. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  51. };
  52. Color3.prototype.scale = function (scale) {
  53. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  54. };
  55. Color3.prototype.scaleToRef = function (scale, result) {
  56. result.r = this.r * scale;
  57. result.g = this.g * scale;
  58. result.b = this.b * scale;
  59. };
  60. Color3.prototype.add = function (otherColor) {
  61. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  62. };
  63. Color3.prototype.addToRef = function (otherColor, result) {
  64. result.r = this.r + otherColor.r;
  65. result.g = this.g + otherColor.g;
  66. result.b = this.b + otherColor.b;
  67. };
  68. Color3.prototype.subtract = function (otherColor) {
  69. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  70. };
  71. Color3.prototype.subtractToRef = function (otherColor, result) {
  72. result.r = this.r - otherColor.r;
  73. result.g = this.g - otherColor.g;
  74. result.b = this.b - otherColor.b;
  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. };
  84. Color3.prototype.copyFromFloats = function (r, g, b) {
  85. this.r = r;
  86. this.g = g;
  87. this.b = b;
  88. };
  89. // Statics
  90. Color3.FromArray = function (array, offset) {
  91. if (typeof offset === "undefined") { offset = 0; }
  92. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  93. };
  94. Color3.FromInts = function (r, g, b) {
  95. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  96. };
  97. Color3.Lerp = function (start, end, amount) {
  98. var r = start.r + ((end.r - start.r) * amount);
  99. var g = start.g + ((end.g - start.g) * amount);
  100. var b = start.b + ((end.b - start.b) * amount);
  101. return new Color3(r, g, b);
  102. };
  103. Color3.Red = function () {
  104. return new Color3(1, 0, 0);
  105. };
  106. Color3.Green = function () {
  107. return new Color3(0, 1, 0);
  108. };
  109. Color3.Blue = function () {
  110. return new Color3(0, 0, 1);
  111. };
  112. Color3.Black = function () {
  113. return new Color3(0, 0, 0);
  114. };
  115. Color3.White = function () {
  116. return new Color3(1, 1, 1);
  117. };
  118. Color3.Purple = function () {
  119. return new Color3(0.5, 0, 0.5);
  120. };
  121. Color3.Magenta = function () {
  122. return new Color3(1, 0, 1);
  123. };
  124. Color3.Yellow = function () {
  125. return new Color3(1, 1, 0);
  126. };
  127. Color3.Gray = function () {
  128. return new Color3(0.5, 0.5, 0.5);
  129. };
  130. return Color3;
  131. })();
  132. BABYLON.Color3 = Color3;
  133. var Color4 = (function () {
  134. function Color4(r, g, b, a) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. this.a = a;
  139. }
  140. // Operators
  141. Color4.prototype.addInPlace = function (right) {
  142. this.r += right.r;
  143. this.g += right.g;
  144. this.b += right.b;
  145. this.a += right.a;
  146. };
  147. Color4.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. Color4.prototype.toArray = function (array, index) {
  153. if (index === undefined) {
  154. index = 0;
  155. }
  156. array[index] = this.r;
  157. array[index + 1] = this.g;
  158. array[index + 2] = this.b;
  159. array[index + 3] = this.a;
  160. };
  161. Color4.prototype.add = function (right) {
  162. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  163. };
  164. Color4.prototype.subtract = function (right) {
  165. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  166. };
  167. Color4.prototype.subtractToRef = function (right, result) {
  168. result.r = this.r - right.r;
  169. result.g = this.g - right.g;
  170. result.b = this.b - right.b;
  171. result.a = this.a - right.a;
  172. };
  173. Color4.prototype.scale = function (scale) {
  174. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  175. };
  176. Color4.prototype.scaleToRef = function (scale, result) {
  177. result.r = this.r * scale;
  178. result.g = this.g * scale;
  179. result.b = this.b * scale;
  180. result.a = this.a * scale;
  181. };
  182. Color4.prototype.toString = function () {
  183. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  184. };
  185. Color4.prototype.clone = function () {
  186. return new Color4(this.r, this.g, this.b, this.a);
  187. };
  188. Color4.prototype.copyFrom = function (source) {
  189. this.r = source.r;
  190. this.g = source.g;
  191. this.b = source.b;
  192. this.a = source.a;
  193. };
  194. // Statics
  195. Color4.Lerp = function (left, right, amount) {
  196. var result = new Color4(0, 0, 0, 0);
  197. Color4.LerpToRef(left, right, amount, result);
  198. return result;
  199. };
  200. Color4.LerpToRef = function (left, right, amount, result) {
  201. result.r = left.r + (right.r - left.r) * amount;
  202. result.g = left.g + (right.g - left.g) * amount;
  203. result.b = left.b + (right.b - left.b) * amount;
  204. result.a = left.a + (right.a - left.a) * amount;
  205. };
  206. Color4.FromArray = function (array, offset) {
  207. if (typeof offset === "undefined") { offset = 0; }
  208. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  209. };
  210. Color4.FromInts = function (r, g, b, a) {
  211. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  212. };
  213. return Color4;
  214. })();
  215. BABYLON.Color4 = Color4;
  216. var Vector2 = (function () {
  217. function Vector2(x, y) {
  218. this.x = x;
  219. this.y = y;
  220. }
  221. Vector2.prototype.toString = function () {
  222. return "{X: " + this.x + " Y:" + this.y + "}";
  223. };
  224. // Operators
  225. Vector2.prototype.toArray = function (array, index) {
  226. if (index === undefined) {
  227. index = 0;
  228. }
  229. array[index] = this.x;
  230. array[index + 1] = this.y;
  231. };
  232. Vector2.prototype.asArray = function () {
  233. var result = [];
  234. this.toArray(result, 0);
  235. return result;
  236. };
  237. Vector2.prototype.copyFrom = function (source) {
  238. this.x = source.x;
  239. this.y = source.y;
  240. };
  241. Vector2.prototype.copyFromFloats = function (x, y) {
  242. this.x = x;
  243. this.y = y;
  244. };
  245. Vector2.prototype.add = function (otherVector) {
  246. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  247. };
  248. Vector2.prototype.addVector3 = function (otherVector) {
  249. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  250. };
  251. Vector2.prototype.subtract = function (otherVector) {
  252. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  253. };
  254. Vector2.prototype.subtractInPlace = function (otherVector) {
  255. this.x -= otherVector.x;
  256. this.y -= otherVector.y;
  257. };
  258. Vector2.prototype.multiplyInPlace = function (otherVector) {
  259. this.x *= otherVector.x;
  260. this.y *= otherVector.y;
  261. };
  262. Vector2.prototype.multiply = function (otherVector) {
  263. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  264. };
  265. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  266. result.x = this.x * otherVector.x;
  267. result.y = this.y * otherVector.y;
  268. };
  269. Vector2.prototype.multiplyByFloats = function (x, y) {
  270. return new Vector2(this.x * x, this.y * y);
  271. };
  272. Vector2.prototype.divide = function (otherVector) {
  273. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  274. };
  275. Vector2.prototype.divideToRef = function (otherVector, result) {
  276. result.x = this.x / otherVector.x;
  277. result.y = this.y / otherVector.y;
  278. };
  279. Vector2.prototype.negate = function () {
  280. return new Vector2(-this.x, -this.y);
  281. };
  282. Vector2.prototype.scaleInPlace = function (scale) {
  283. this.x *= scale;
  284. this.y *= scale;
  285. return this;
  286. };
  287. Vector2.prototype.scale = function (scale) {
  288. return new Vector2(this.x * scale, this.y * scale);
  289. };
  290. Vector2.prototype.equals = function (otherVector) {
  291. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  292. };
  293. // Properties
  294. Vector2.prototype.length = function () {
  295. return Math.sqrt(this.x * this.x + this.y * this.y);
  296. };
  297. Vector2.prototype.lengthSquared = function () {
  298. return (this.x * this.x + this.y * this.y);
  299. };
  300. // Methods
  301. Vector2.prototype.normalize = function () {
  302. var len = this.length();
  303. if (len === 0)
  304. return this;
  305. var num = 1.0 / len;
  306. this.x *= num;
  307. this.y *= num;
  308. return this;
  309. };
  310. Vector2.prototype.clone = function () {
  311. return new Vector2(this.x, this.y);
  312. };
  313. // Statics
  314. Vector2.Zero = function () {
  315. return new Vector2(0, 0);
  316. };
  317. Vector2.FromArray = function (array, offset) {
  318. if (typeof offset === "undefined") { offset = 0; }
  319. return new Vector2(array[offset], array[offset + 1]);
  320. };
  321. Vector2.FromArrayToRef = function (array, offset, result) {
  322. result.x = array[offset];
  323. result.y = array[offset + 1];
  324. };
  325. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  326. var squared = amount * amount;
  327. var cubed = amount * squared;
  328. 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));
  329. 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));
  330. return new Vector2(x, y);
  331. };
  332. Vector2.Clamp = function (value, min, max) {
  333. var x = value.x;
  334. x = (x > max.x) ? max.x : x;
  335. x = (x < min.x) ? min.x : x;
  336. var y = value.y;
  337. y = (y > max.y) ? max.y : y;
  338. y = (y < min.y) ? min.y : y;
  339. return new Vector2(x, y);
  340. };
  341. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  342. var squared = amount * amount;
  343. var cubed = amount * squared;
  344. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  345. var part2 = (-2.0 * cubed) + (3.0 * squared);
  346. var part3 = (cubed - (2.0 * squared)) + amount;
  347. var part4 = cubed - squared;
  348. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  349. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Lerp = function (start, end, amount) {
  353. var x = start.x + ((end.x - start.x) * amount);
  354. var y = start.y + ((end.y - start.y) * amount);
  355. return new Vector2(x, y);
  356. };
  357. Vector2.Dot = function (left, right) {
  358. return left.x * right.x + left.y * right.y;
  359. };
  360. Vector2.Normalize = function (vector) {
  361. var newVector = vector.clone();
  362. newVector.normalize();
  363. return newVector;
  364. };
  365. Vector2.Minimize = function (left, right) {
  366. var x = (left.x < right.x) ? left.x : right.x;
  367. var y = (left.y < right.y) ? left.y : right.y;
  368. return new Vector2(x, y);
  369. };
  370. Vector2.Maximize = function (left, right) {
  371. var x = (left.x > right.x) ? left.x : right.x;
  372. var y = (left.y > right.y) ? left.y : right.y;
  373. return new Vector2(x, y);
  374. };
  375. Vector2.Transform = function (vector, transformation) {
  376. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  377. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  378. return new Vector2(x, y);
  379. };
  380. Vector2.Distance = function (value1, value2) {
  381. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  382. };
  383. Vector2.DistanceSquared = function (value1, value2) {
  384. var x = value1.x - value2.x;
  385. var y = value1.y - value2.y;
  386. return (x * x) + (y * y);
  387. };
  388. return Vector2;
  389. })();
  390. BABYLON.Vector2 = Vector2;
  391. var Vector3 = (function () {
  392. function Vector3(x, y, z) {
  393. this.x = x;
  394. this.y = y;
  395. this.z = z;
  396. }
  397. Vector3.prototype.toString = function () {
  398. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  399. };
  400. // Operators
  401. Vector3.prototype.asArray = function () {
  402. var result = [];
  403. this.toArray(result, 0);
  404. return result;
  405. };
  406. Vector3.prototype.toArray = function (array, index) {
  407. if (index === undefined) {
  408. index = 0;
  409. }
  410. array[index] = this.x;
  411. array[index + 1] = this.y;
  412. array[index + 2] = this.z;
  413. };
  414. Vector3.prototype.addInPlace = function (otherVector) {
  415. this.x += otherVector.x;
  416. this.y += otherVector.y;
  417. this.z += otherVector.z;
  418. };
  419. Vector3.prototype.add = function (otherVector) {
  420. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  421. };
  422. Vector3.prototype.addToRef = function (otherVector, result) {
  423. result.x = this.x + otherVector.x;
  424. result.y = this.y + otherVector.y;
  425. result.z = this.z + otherVector.z;
  426. };
  427. Vector3.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. this.z -= otherVector.z;
  431. };
  432. Vector3.prototype.subtract = function (otherVector) {
  433. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  434. };
  435. Vector3.prototype.subtractToRef = function (otherVector, result) {
  436. result.x = this.x - otherVector.x;
  437. result.y = this.y - otherVector.y;
  438. result.z = this.z - otherVector.z;
  439. };
  440. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  441. return new Vector3(this.x - x, this.y - y, this.z - z);
  442. };
  443. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  444. result.x = this.x - x;
  445. result.y = this.y - y;
  446. result.z = this.z - z;
  447. };
  448. Vector3.prototype.negate = function () {
  449. return new Vector3(-this.x, -this.y, -this.z);
  450. };
  451. Vector3.prototype.scaleInPlace = function (scale) {
  452. this.x *= scale;
  453. this.y *= scale;
  454. this.z *= scale;
  455. return this;
  456. };
  457. Vector3.prototype.scale = function (scale) {
  458. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  459. };
  460. Vector3.prototype.scaleToRef = function (scale, result) {
  461. result.x = this.x * scale;
  462. result.y = this.y * scale;
  463. result.z = this.z * scale;
  464. };
  465. Vector3.prototype.equals = function (otherVector) {
  466. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  467. };
  468. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  469. 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;
  470. };
  471. Vector3.prototype.equalsToFloats = function (x, y, z) {
  472. return this.x === x && this.y === y && this.z === z;
  473. };
  474. Vector3.prototype.multiplyInPlace = function (otherVector) {
  475. this.x *= otherVector.x;
  476. this.y *= otherVector.y;
  477. this.z *= otherVector.z;
  478. };
  479. Vector3.prototype.multiply = function (otherVector) {
  480. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  481. };
  482. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  483. result.x = this.x * otherVector.x;
  484. result.y = this.y * otherVector.y;
  485. result.z = this.z * otherVector.z;
  486. };
  487. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  488. return new Vector3(this.x * x, this.y * y, this.z * z);
  489. };
  490. Vector3.prototype.divide = function (otherVector) {
  491. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  492. };
  493. Vector3.prototype.divideToRef = function (otherVector, result) {
  494. result.x = this.x / otherVector.x;
  495. result.y = this.y / otherVector.y;
  496. result.z = this.z / otherVector.z;
  497. };
  498. Vector3.prototype.MinimizeInPlace = function (other) {
  499. if (other.x < this.x)
  500. this.x = other.x;
  501. if (other.y < this.y)
  502. this.y = other.y;
  503. if (other.z < this.z)
  504. this.z = other.z;
  505. };
  506. Vector3.prototype.MaximizeInPlace = function (other) {
  507. if (other.x > this.x)
  508. this.x = other.x;
  509. if (other.y > this.y)
  510. this.y = other.y;
  511. if (other.z > this.z)
  512. this.z = other.z;
  513. };
  514. // Properties
  515. Vector3.prototype.length = function () {
  516. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  517. };
  518. Vector3.prototype.lengthSquared = function () {
  519. return (this.x * this.x + this.y * this.y + this.z * this.z);
  520. };
  521. // Methods
  522. Vector3.prototype.normalize = function () {
  523. var len = this.length();
  524. if (len === 0)
  525. return this;
  526. var num = 1.0 / len;
  527. this.x *= num;
  528. this.y *= num;
  529. this.z *= num;
  530. return this;
  531. };
  532. Vector3.prototype.clone = function () {
  533. return new Vector3(this.x, this.y, this.z);
  534. };
  535. Vector3.prototype.copyFrom = function (source) {
  536. this.x = source.x;
  537. this.y = source.y;
  538. this.z = source.z;
  539. };
  540. Vector3.prototype.copyFromFloats = function (x, y, z) {
  541. this.x = x;
  542. this.y = y;
  543. this.z = z;
  544. };
  545. // Statics
  546. Vector3.FromArray = function (array, offset) {
  547. if (!offset) {
  548. offset = 0;
  549. }
  550. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  551. };
  552. Vector3.FromArrayToRef = function (array, offset, result) {
  553. result.x = array[offset];
  554. result.y = array[offset + 1];
  555. result.z = array[offset + 2];
  556. };
  557. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  558. result.x = array[offset];
  559. result.y = array[offset + 1];
  560. result.z = array[offset + 2];
  561. };
  562. Vector3.FromFloatsToRef = function (x, y, z, result) {
  563. result.x = x;
  564. result.y = y;
  565. result.z = z;
  566. };
  567. Vector3.Zero = function () {
  568. return new Vector3(0, 0, 0);
  569. };
  570. Vector3.Up = function () {
  571. return new Vector3(0, 1.0, 0);
  572. };
  573. Vector3.TransformCoordinates = function (vector, transformation) {
  574. var result = Vector3.Zero();
  575. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  576. return result;
  577. };
  578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  581. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  582. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  583. result.x = x / w;
  584. result.y = y / w;
  585. result.z = z / w;
  586. };
  587. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  588. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  589. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  590. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  591. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  592. result.x = rx / rw;
  593. result.y = ry / rw;
  594. result.z = rz / rw;
  595. };
  596. Vector3.TransformNormal = function (vector, transformation) {
  597. var result = Vector3.Zero();
  598. Vector3.TransformNormalToRef(vector, transformation, result);
  599. return result;
  600. };
  601. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  602. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  603. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  604. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  605. };
  606. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  607. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  608. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  609. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  610. };
  611. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  612. var squared = amount * amount;
  613. var cubed = amount * squared;
  614. 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));
  615. 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));
  616. 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));
  617. return new Vector3(x, y, z);
  618. };
  619. Vector3.Clamp = function (value, min, max) {
  620. var x = value.x;
  621. x = (x > max.x) ? max.x : x;
  622. x = (x < min.x) ? min.x : x;
  623. var y = value.y;
  624. y = (y > max.y) ? max.y : y;
  625. y = (y < min.y) ? min.y : y;
  626. var z = value.z;
  627. z = (z > max.z) ? max.z : z;
  628. z = (z < min.z) ? min.z : z;
  629. return new Vector3(x, y, z);
  630. };
  631. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  632. var squared = amount * amount;
  633. var cubed = amount * squared;
  634. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  635. var part2 = (-2.0 * cubed) + (3.0 * squared);
  636. var part3 = (cubed - (2.0 * squared)) + amount;
  637. var part4 = cubed - squared;
  638. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  639. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  640. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  641. return new Vector3(x, y, z);
  642. };
  643. Vector3.Lerp = function (start, end, amount) {
  644. var x = start.x + ((end.x - start.x) * amount);
  645. var y = start.y + ((end.y - start.y) * amount);
  646. var z = start.z + ((end.z - start.z) * amount);
  647. return new Vector3(x, y, z);
  648. };
  649. Vector3.Dot = function (left, right) {
  650. return (left.x * right.x + left.y * right.y + left.z * right.z);
  651. };
  652. Vector3.Cross = function (left, right) {
  653. var result = Vector3.Zero();
  654. Vector3.CrossToRef(left, right, result);
  655. return result;
  656. };
  657. Vector3.CrossToRef = function (left, right, result) {
  658. result.x = left.y * right.z - left.z * right.y;
  659. result.y = left.z * right.x - left.x * right.z;
  660. result.z = left.x * right.y - left.y * right.x;
  661. };
  662. Vector3.Normalize = function (vector) {
  663. var result = Vector3.Zero();
  664. Vector3.NormalizeToRef(vector, result);
  665. return result;
  666. };
  667. Vector3.NormalizeToRef = function (vector, result) {
  668. result.copyFrom(vector);
  669. result.normalize();
  670. };
  671. Vector3.Project = function (vector, world, transform, viewport) {
  672. var cw = viewport.width;
  673. var ch = viewport.height;
  674. var cx = viewport.x;
  675. var cy = viewport.y;
  676. 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);
  677. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  678. return Vector3.TransformCoordinates(vector, finalMatrix);
  679. };
  680. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  681. var matrix = world.multiply(transform);
  682. matrix.invert();
  683. source.x = source.x / viewportWidth * 2 - 1;
  684. source.y = -(source.y / viewportHeight * 2 - 1);
  685. var vector = Vector3.TransformCoordinates(source, matrix);
  686. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  687. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  688. vector = vector.scale(1.0 / num);
  689. }
  690. return vector;
  691. };
  692. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  693. var matrix = world.multiply(view).multiply(projection);
  694. matrix.invert();
  695. source.x = source.x / viewportWidth * 2 - 1;
  696. source.y = -(source.y / viewportHeight * 2 - 1);
  697. var vector = Vector3.TransformCoordinates(source, matrix);
  698. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  699. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  700. vector = vector.scale(1.0 / num);
  701. }
  702. return vector;
  703. };
  704. Vector3.Minimize = function (left, right) {
  705. var min = left.clone();
  706. min.MinimizeInPlace(right);
  707. return min;
  708. };
  709. Vector3.Maximize = function (left, right) {
  710. var max = left.clone();
  711. max.MaximizeInPlace(right);
  712. return max;
  713. };
  714. Vector3.Distance = function (value1, value2) {
  715. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  716. };
  717. Vector3.DistanceSquared = function (value1, value2) {
  718. var x = value1.x - value2.x;
  719. var y = value1.y - value2.y;
  720. var z = value1.z - value2.z;
  721. return (x * x) + (y * y) + (z * z);
  722. };
  723. Vector3.Center = function (value1, value2) {
  724. var center = value1.add(value2);
  725. center.scaleInPlace(0.5);
  726. return center;
  727. };
  728. return Vector3;
  729. })();
  730. BABYLON.Vector3 = Vector3;
  731. //Vector4 class created for EulerAngle class conversion to Quaternion
  732. var Vector4 = (function () {
  733. function Vector4(x, y, z, w) {
  734. this.x = x;
  735. this.y = y;
  736. this.z = z;
  737. this.w = w;
  738. }
  739. Vector4.prototype.toString = function () {
  740. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  741. };
  742. // Operators
  743. Vector4.prototype.asArray = function () {
  744. var result = [];
  745. this.toArray(result, 0);
  746. return result;
  747. };
  748. Vector4.prototype.toArray = function (array, index) {
  749. if (index === undefined) {
  750. index = 0;
  751. }
  752. array[index] = this.x;
  753. array[index + 1] = this.y;
  754. array[index + 2] = this.z;
  755. array[index + 3] = this.w;
  756. };
  757. Vector4.prototype.addInPlace = function (otherVector) {
  758. this.x += otherVector.x;
  759. this.y += otherVector.y;
  760. this.z += otherVector.z;
  761. this.w += otherVector.w;
  762. };
  763. Vector4.prototype.add = function (otherVector) {
  764. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  765. };
  766. Vector4.prototype.addToRef = function (otherVector, result) {
  767. result.x = this.x + otherVector.x;
  768. result.y = this.y + otherVector.y;
  769. result.z = this.z + otherVector.z;
  770. result.w = this.w + otherVector.w;
  771. };
  772. Vector4.prototype.subtractInPlace = function (otherVector) {
  773. this.x -= otherVector.x;
  774. this.y -= otherVector.y;
  775. this.z -= otherVector.z;
  776. this.w -= otherVector.w;
  777. };
  778. Vector4.prototype.subtract = function (otherVector) {
  779. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  780. };
  781. Vector4.prototype.subtractToRef = function (otherVector, result) {
  782. result.x = this.x - otherVector.x;
  783. result.y = this.y - otherVector.y;
  784. result.z = this.z - otherVector.z;
  785. result.w = this.w - otherVector.w;
  786. };
  787. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  788. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  789. };
  790. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  791. result.x = this.x - x;
  792. result.y = this.y - y;
  793. result.z = this.z - z;
  794. result.w = this.w - w;
  795. };
  796. Vector4.prototype.negate = function () {
  797. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  798. };
  799. Vector4.prototype.scaleInPlace = function (scale) {
  800. this.x *= scale;
  801. this.y *= scale;
  802. this.z *= scale;
  803. this.w *= scale;
  804. return this;
  805. };
  806. Vector4.prototype.scale = function (scale) {
  807. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  808. };
  809. Vector4.prototype.scaleToRef = function (scale, result) {
  810. result.x = this.x * scale;
  811. result.y = this.y * scale;
  812. result.z = this.z * scale;
  813. result.w = this.w * scale;
  814. };
  815. Vector4.prototype.equals = function (otherVector) {
  816. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  817. };
  818. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  819. 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;
  820. };
  821. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  822. return this.x === x && this.y === y && this.z === z && this.w === w;
  823. };
  824. Vector4.prototype.multiplyInPlace = function (otherVector) {
  825. this.x *= otherVector.x;
  826. this.y *= otherVector.y;
  827. this.z *= otherVector.z;
  828. this.w *= otherVector.w;
  829. };
  830. Vector4.prototype.multiply = function (otherVector) {
  831. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  832. };
  833. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  834. result.x = this.x * otherVector.x;
  835. result.y = this.y * otherVector.y;
  836. result.z = this.z * otherVector.z;
  837. result.w = this.w * otherVector.w;
  838. };
  839. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  840. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  841. };
  842. Vector4.prototype.divide = function (otherVector) {
  843. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  844. };
  845. Vector4.prototype.divideToRef = function (otherVector, result) {
  846. result.x = this.x / otherVector.x;
  847. result.y = this.y / otherVector.y;
  848. result.z = this.z / otherVector.z;
  849. result.w = this.w / otherVector.w;
  850. };
  851. Vector4.prototype.MinimizeInPlace = function (other) {
  852. if (other.x < this.x)
  853. this.x = other.x;
  854. if (other.y < this.y)
  855. this.y = other.y;
  856. if (other.z < this.z)
  857. this.z = other.z;
  858. if (other.w < this.w)
  859. this.w = other.w;
  860. };
  861. Vector4.prototype.MaximizeInPlace = function (other) {
  862. if (other.x > this.x)
  863. this.x = other.x;
  864. if (other.y > this.y)
  865. this.y = other.y;
  866. if (other.z > this.z)
  867. this.z = other.z;
  868. if (other.w > this.w)
  869. this.w = other.w;
  870. };
  871. // Properties
  872. Vector4.prototype.length = function () {
  873. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  874. };
  875. Vector4.prototype.lengthSquared = function () {
  876. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  877. };
  878. // Methods
  879. Vector4.prototype.normalize = function () {
  880. var len = this.length();
  881. if (len === 0)
  882. return this;
  883. var num = 1.0 / len;
  884. this.x *= num;
  885. this.y *= num;
  886. this.z *= num;
  887. this.w *= num;
  888. return this;
  889. };
  890. Vector4.prototype.clone = function () {
  891. return new Vector4(this.x, this.y, this.z, this.w);
  892. };
  893. Vector4.prototype.copyFrom = function (source) {
  894. this.x = source.x;
  895. this.y = source.y;
  896. this.z = source.z;
  897. this.w = source.w;
  898. };
  899. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  900. this.x = x;
  901. this.y = y;
  902. this.z = z;
  903. this.w = w;
  904. };
  905. // Statics
  906. Vector4.FromArray = function (array, offset) {
  907. if (!offset) {
  908. offset = 0;
  909. }
  910. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  911. };
  912. Vector4.FromArrayToRef = function (array, offset, result) {
  913. result.x = array[offset];
  914. result.y = array[offset + 1];
  915. result.z = array[offset + 2];
  916. result.w = array[offset + 3];
  917. };
  918. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  919. result.x = array[offset];
  920. result.y = array[offset + 1];
  921. result.z = array[offset + 2];
  922. result.w = array[offset + 3];
  923. };
  924. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  925. result.x = x;
  926. result.y = y;
  927. result.z = z;
  928. result.w = w;
  929. };
  930. Vector4.Zero = function () {
  931. return new Vector4(0, 0, 0, 0);
  932. };
  933. Vector4.Normalize = function (vector) {
  934. var result = Vector4.Zero();
  935. Vector4.NormalizeToRef(vector, result);
  936. return result;
  937. };
  938. Vector4.NormalizeToRef = function (vector, result) {
  939. result.copyFrom(vector);
  940. result.normalize();
  941. };
  942. Vector4.Minimize = function (left, right) {
  943. var min = left.clone();
  944. min.MinimizeInPlace(right);
  945. return min;
  946. };
  947. Vector4.Maximize = function (left, right) {
  948. var max = left.clone();
  949. max.MaximizeInPlace(right);
  950. return max;
  951. };
  952. Vector4.Distance = function (value1, value2) {
  953. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  954. };
  955. Vector4.DistanceSquared = function (value1, value2) {
  956. var x = value1.x - value2.x;
  957. var y = value1.y - value2.y;
  958. var z = value1.z - value2.z;
  959. var w = value1.w - value2.w;
  960. return (x * x) + (y * y) + (z * z) + (w * w);
  961. };
  962. Vector4.Center = function (value1, value2) {
  963. var center = value1.add(value2);
  964. center.scaleInPlace(0.5);
  965. return center;
  966. };
  967. return Vector4;
  968. })();
  969. BABYLON.Vector4 = Vector4;
  970. var Quaternion = (function () {
  971. function Quaternion(x, y, z, w) {
  972. if (typeof x === "undefined") { x = 0; }
  973. if (typeof y === "undefined") { y = 0; }
  974. if (typeof z === "undefined") { z = 0; }
  975. if (typeof w === "undefined") { w = 1; }
  976. this.x = x;
  977. this.y = y;
  978. this.z = z;
  979. this.w = w;
  980. }
  981. Quaternion.prototype.toString = function () {
  982. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  983. };
  984. Quaternion.prototype.asArray = function () {
  985. return [this.x, this.y, this.z, this.w];
  986. };
  987. Quaternion.prototype.equals = function (otherQuaternion) {
  988. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  989. };
  990. Quaternion.prototype.clone = function () {
  991. return new Quaternion(this.x, this.y, this.z, this.w);
  992. };
  993. Quaternion.prototype.copyFrom = function (other) {
  994. this.x = other.x;
  995. this.y = other.y;
  996. this.z = other.z;
  997. this.w = other.w;
  998. };
  999. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1000. this.x = x;
  1001. this.y = y;
  1002. this.z = z;
  1003. this.w = w;
  1004. };
  1005. Quaternion.prototype.add = function (other) {
  1006. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1007. };
  1008. Quaternion.prototype.subtract = function (other) {
  1009. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1010. };
  1011. Quaternion.prototype.scale = function (value) {
  1012. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1013. };
  1014. Quaternion.prototype.multiply = function (q1) {
  1015. var result = new Quaternion(0, 0, 0, 1.0);
  1016. this.multiplyToRef(q1, result);
  1017. return result;
  1018. };
  1019. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1020. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1021. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1022. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1023. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1024. };
  1025. Quaternion.prototype.length = function () {
  1026. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1027. };
  1028. Quaternion.prototype.normalize = function () {
  1029. var length = 1.0 / this.length();
  1030. this.x *= length;
  1031. this.y *= length;
  1032. this.z *= length;
  1033. this.w *= length;
  1034. };
  1035. Quaternion.prototype.toEulerAngles = function () {
  1036. var result = Vector3.Zero();
  1037. this.toEulerAnglesToRef(result);
  1038. return result;
  1039. };
  1040. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1041. //result is an EulerAngles in the in the z-x-z convention
  1042. var qx = this.x;
  1043. var qy = this.y;
  1044. var qz = this.z;
  1045. var qw = this.w;
  1046. var qxy = qx * qy;
  1047. var qxz = qx * qz;
  1048. var qwy = qw * qy;
  1049. var qwz = qw * qz;
  1050. var qwx = qw * qx;
  1051. var qyz = qy * qz;
  1052. var sqx = qx * qx;
  1053. var sqy = qy * qy;
  1054. var determinant = sqx + sqy;
  1055. if (determinant !== 0.000 && determinant !== 1.000) {
  1056. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1057. result.y = Math.acos(1 - 2 * determinant);
  1058. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1059. } else {
  1060. if (determinant === 0.0) {
  1061. result.x = 0.0;
  1062. result.y = 0.0;
  1063. 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)
  1064. } else {
  1065. 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)
  1066. result.y = Math.PI;
  1067. result.z = 0.0;
  1068. }
  1069. }
  1070. };
  1071. Quaternion.prototype.toRotationMatrix = function (result) {
  1072. var xx = this.x * this.x;
  1073. var yy = this.y * this.y;
  1074. var zz = this.z * this.z;
  1075. var xy = this.x * this.y;
  1076. var zw = this.z * this.w;
  1077. var zx = this.z * this.x;
  1078. var yw = this.y * this.w;
  1079. var yz = this.y * this.z;
  1080. var xw = this.x * this.w;
  1081. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1082. result.m[1] = 2.0 * (xy + zw);
  1083. result.m[2] = 2.0 * (zx - yw);
  1084. result.m[3] = 0;
  1085. result.m[4] = 2.0 * (xy - zw);
  1086. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1087. result.m[6] = 2.0 * (yz + xw);
  1088. result.m[7] = 0;
  1089. result.m[8] = 2.0 * (zx + yw);
  1090. result.m[9] = 2.0 * (yz - xw);
  1091. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1092. result.m[11] = 0;
  1093. result.m[12] = 0;
  1094. result.m[13] = 0;
  1095. result.m[14] = 0;
  1096. result.m[15] = 1.0;
  1097. };
  1098. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1099. var data = matrix.m;
  1100. var m11 = data[0], m12 = data[4], m13 = data[8];
  1101. var m21 = data[1], m22 = data[5], m23 = data[9];
  1102. var m31 = data[2], m32 = data[6], m33 = data[10];
  1103. var trace = m11 + m22 + m33;
  1104. var s;
  1105. if (trace > 0) {
  1106. s = 0.5 / Math.sqrt(trace + 1.0);
  1107. this.w = 0.25 / s;
  1108. this.x = (m32 - m23) * s;
  1109. this.y = (m13 - m31) * s;
  1110. this.z = (m21 - m12) * s;
  1111. return;
  1112. }
  1113. if (m11 > m22 && m11 > m33) {
  1114. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1115. this.w = (m32 - m23) / s;
  1116. this.x = 0.25 * s;
  1117. this.y = (m12 + m21) / s;
  1118. this.z = (m13 + m31) / s;
  1119. return;
  1120. }
  1121. if (m22 > m33) {
  1122. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1123. this.w = (m13 - m31) / s;
  1124. this.x = (m12 + m21) / s;
  1125. this.y = 0.25 * s;
  1126. this.z = (m23 + m32) / s;
  1127. return;
  1128. }
  1129. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1130. this.w = (m21 - m12) / s;
  1131. this.x = (m13 + m31) / s;
  1132. this.y = (m23 + m32) / s;
  1133. this.z = 0.25 * s;
  1134. };
  1135. // Statics
  1136. Quaternion.Inverse = function (q) {
  1137. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1138. };
  1139. Quaternion.Identity = function () {
  1140. return new Quaternion(0, 0, 0, 1);
  1141. };
  1142. Quaternion.RotationAxis = function (axis, angle) {
  1143. var result = new Quaternion();
  1144. var sin = Math.sin(angle / 2);
  1145. result.w = Math.cos(angle / 2);
  1146. result.x = axis.x * sin;
  1147. result.y = axis.y * sin;
  1148. result.z = axis.z * sin;
  1149. return result;
  1150. };
  1151. Quaternion.FromArray = function (array, offset) {
  1152. if (!offset) {
  1153. offset = 0;
  1154. }
  1155. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1156. };
  1157. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1158. var result = new Quaternion();
  1159. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1160. return result;
  1161. };
  1162. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1163. var halfRoll = roll * 0.5;
  1164. var halfPitch = pitch * 0.5;
  1165. var halfYaw = yaw * 0.5;
  1166. var sinRoll = Math.sin(halfRoll);
  1167. var cosRoll = Math.cos(halfRoll);
  1168. var sinPitch = Math.sin(halfPitch);
  1169. var cosPitch = Math.cos(halfPitch);
  1170. var sinYaw = Math.sin(halfYaw);
  1171. var cosYaw = Math.cos(halfYaw);
  1172. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1173. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1174. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1175. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1176. };
  1177. Quaternion.Slerp = function (left, right, amount) {
  1178. var num2;
  1179. var num3;
  1180. var num = amount;
  1181. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1182. var flag = false;
  1183. if (num4 < 0) {
  1184. flag = true;
  1185. num4 = -num4;
  1186. }
  1187. if (num4 > 0.999999) {
  1188. num3 = 1 - num;
  1189. num2 = flag ? -num : num;
  1190. } else {
  1191. var num5 = Math.acos(num4);
  1192. var num6 = (1.0 / Math.sin(num5));
  1193. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1194. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1195. }
  1196. 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));
  1197. };
  1198. return Quaternion;
  1199. })();
  1200. BABYLON.Quaternion = Quaternion;
  1201. var Matrix = (function () {
  1202. function Matrix() {
  1203. this.m = new Float32Array(16);
  1204. }
  1205. // Properties
  1206. Matrix.prototype.isIdentity = function () {
  1207. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1208. return false;
  1209. 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)
  1210. return false;
  1211. return true;
  1212. };
  1213. Matrix.prototype.determinant = function () {
  1214. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1215. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1216. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1217. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1218. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1219. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1220. 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))));
  1221. };
  1222. // Methods
  1223. Matrix.prototype.toArray = function () {
  1224. return this.m;
  1225. };
  1226. Matrix.prototype.asArray = function () {
  1227. return this.toArray();
  1228. };
  1229. Matrix.prototype.invert = function () {
  1230. this.invertToRef(this);
  1231. };
  1232. Matrix.prototype.invertToRef = function (other) {
  1233. var l1 = this.m[0];
  1234. var l2 = this.m[1];
  1235. var l3 = this.m[2];
  1236. var l4 = this.m[3];
  1237. var l5 = this.m[4];
  1238. var l6 = this.m[5];
  1239. var l7 = this.m[6];
  1240. var l8 = this.m[7];
  1241. var l9 = this.m[8];
  1242. var l10 = this.m[9];
  1243. var l11 = this.m[10];
  1244. var l12 = this.m[11];
  1245. var l13 = this.m[12];
  1246. var l14 = this.m[13];
  1247. var l15 = this.m[14];
  1248. var l16 = this.m[15];
  1249. var l17 = (l11 * l16) - (l12 * l15);
  1250. var l18 = (l10 * l16) - (l12 * l14);
  1251. var l19 = (l10 * l15) - (l11 * l14);
  1252. var l20 = (l9 * l16) - (l12 * l13);
  1253. var l21 = (l9 * l15) - (l11 * l13);
  1254. var l22 = (l9 * l14) - (l10 * l13);
  1255. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1256. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1257. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1258. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1259. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1260. var l28 = (l7 * l16) - (l8 * l15);
  1261. var l29 = (l6 * l16) - (l8 * l14);
  1262. var l30 = (l6 * l15) - (l7 * l14);
  1263. var l31 = (l5 * l16) - (l8 * l13);
  1264. var l32 = (l5 * l15) - (l7 * l13);
  1265. var l33 = (l5 * l14) - (l6 * l13);
  1266. var l34 = (l7 * l12) - (l8 * l11);
  1267. var l35 = (l6 * l12) - (l8 * l10);
  1268. var l36 = (l6 * l11) - (l7 * l10);
  1269. var l37 = (l5 * l12) - (l8 * l9);
  1270. var l38 = (l5 * l11) - (l7 * l9);
  1271. var l39 = (l5 * l10) - (l6 * l9);
  1272. other.m[0] = l23 * l27;
  1273. other.m[4] = l24 * l27;
  1274. other.m[8] = l25 * l27;
  1275. other.m[12] = l26 * l27;
  1276. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1277. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1278. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1279. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1280. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1281. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1282. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1283. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1284. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1285. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1286. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1287. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1288. };
  1289. Matrix.prototype.setTranslation = function (vector3) {
  1290. this.m[12] = vector3.x;
  1291. this.m[13] = vector3.y;
  1292. this.m[14] = vector3.z;
  1293. };
  1294. Matrix.prototype.multiply = function (other) {
  1295. var result = new Matrix();
  1296. this.multiplyToRef(other, result);
  1297. return result;
  1298. };
  1299. Matrix.prototype.copyFrom = function (other) {
  1300. for (var index = 0; index < 16; index++) {
  1301. this.m[index] = other.m[index];
  1302. }
  1303. };
  1304. Matrix.prototype.copyToArray = function (array, offset) {
  1305. if (typeof offset === "undefined") { offset = 0; }
  1306. for (var index = 0; index < 16; index++) {
  1307. array[offset + index] = this.m[index];
  1308. }
  1309. };
  1310. Matrix.prototype.multiplyToRef = function (other, result) {
  1311. this.multiplyToArray(other, result.m, 0);
  1312. };
  1313. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1314. var tm0 = this.m[0];
  1315. var tm1 = this.m[1];
  1316. var tm2 = this.m[2];
  1317. var tm3 = this.m[3];
  1318. var tm4 = this.m[4];
  1319. var tm5 = this.m[5];
  1320. var tm6 = this.m[6];
  1321. var tm7 = this.m[7];
  1322. var tm8 = this.m[8];
  1323. var tm9 = this.m[9];
  1324. var tm10 = this.m[10];
  1325. var tm11 = this.m[11];
  1326. var tm12 = this.m[12];
  1327. var tm13 = this.m[13];
  1328. var tm14 = this.m[14];
  1329. var tm15 = this.m[15];
  1330. var om0 = other.m[0];
  1331. var om1 = other.m[1];
  1332. var om2 = other.m[2];
  1333. var om3 = other.m[3];
  1334. var om4 = other.m[4];
  1335. var om5 = other.m[5];
  1336. var om6 = other.m[6];
  1337. var om7 = other.m[7];
  1338. var om8 = other.m[8];
  1339. var om9 = other.m[9];
  1340. var om10 = other.m[10];
  1341. var om11 = other.m[11];
  1342. var om12 = other.m[12];
  1343. var om13 = other.m[13];
  1344. var om14 = other.m[14];
  1345. var om15 = other.m[15];
  1346. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1347. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1348. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1349. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1350. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1351. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1352. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1353. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1354. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1355. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1356. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1357. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1358. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1359. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1360. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1361. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1362. };
  1363. Matrix.prototype.equals = function (value) {
  1364. 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]);
  1365. };
  1366. Matrix.prototype.clone = function () {
  1367. 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]);
  1368. };
  1369. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1370. translation.x = this.m[12];
  1371. translation.y = this.m[13];
  1372. translation.z = this.m[14];
  1373. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1374. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1375. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1376. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1377. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1378. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1379. if (scale.x == 0 || scale.y == 0 || scale.z == 0) {
  1380. rotation.x = 0;
  1381. rotation.y = 0;
  1382. rotation.z = 0;
  1383. rotation.w = 1;
  1384. return false;
  1385. }
  1386. var rotationMatrix = BABYLON.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);
  1387. rotation.fromRotationMatrix(rotationMatrix);
  1388. return true;
  1389. };
  1390. // Statics
  1391. Matrix.FromArray = function (array, offset) {
  1392. var result = new Matrix();
  1393. if (!offset) {
  1394. offset = 0;
  1395. }
  1396. Matrix.FromArrayToRef(array, offset, result);
  1397. return result;
  1398. };
  1399. Matrix.FromArrayToRef = function (array, offset, result) {
  1400. for (var index = 0; index < 16; index++) {
  1401. result.m[index] = array[index + offset];
  1402. }
  1403. };
  1404. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1405. result.m[0] = initialM11;
  1406. result.m[1] = initialM12;
  1407. result.m[2] = initialM13;
  1408. result.m[3] = initialM14;
  1409. result.m[4] = initialM21;
  1410. result.m[5] = initialM22;
  1411. result.m[6] = initialM23;
  1412. result.m[7] = initialM24;
  1413. result.m[8] = initialM31;
  1414. result.m[9] = initialM32;
  1415. result.m[10] = initialM33;
  1416. result.m[11] = initialM34;
  1417. result.m[12] = initialM41;
  1418. result.m[13] = initialM42;
  1419. result.m[14] = initialM43;
  1420. result.m[15] = initialM44;
  1421. };
  1422. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1423. var result = new Matrix();
  1424. result.m[0] = initialM11;
  1425. result.m[1] = initialM12;
  1426. result.m[2] = initialM13;
  1427. result.m[3] = initialM14;
  1428. result.m[4] = initialM21;
  1429. result.m[5] = initialM22;
  1430. result.m[6] = initialM23;
  1431. result.m[7] = initialM24;
  1432. result.m[8] = initialM31;
  1433. result.m[9] = initialM32;
  1434. result.m[10] = initialM33;
  1435. result.m[11] = initialM34;
  1436. result.m[12] = initialM41;
  1437. result.m[13] = initialM42;
  1438. result.m[14] = initialM43;
  1439. result.m[15] = initialM44;
  1440. return result;
  1441. };
  1442. Matrix.Compose = function (scale, rotation, translation) {
  1443. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1444. var rotationMatrix = Matrix.Identity();
  1445. rotation.toRotationMatrix(rotationMatrix);
  1446. result = result.multiply(rotationMatrix);
  1447. result.setTranslation(translation);
  1448. return result;
  1449. };
  1450. Matrix.Identity = function () {
  1451. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1452. };
  1453. Matrix.IdentityToRef = function (result) {
  1454. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1455. };
  1456. Matrix.Zero = function () {
  1457. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1458. };
  1459. Matrix.RotationX = function (angle) {
  1460. var result = new Matrix();
  1461. Matrix.RotationXToRef(angle, result);
  1462. return result;
  1463. };
  1464. Matrix.Invert = function (source) {
  1465. var result = new Matrix();
  1466. source.invertToRef(result);
  1467. return result;
  1468. };
  1469. Matrix.RotationXToRef = function (angle, result) {
  1470. var s = Math.sin(angle);
  1471. var c = Math.cos(angle);
  1472. result.m[0] = 1.0;
  1473. result.m[15] = 1.0;
  1474. result.m[5] = c;
  1475. result.m[10] = c;
  1476. result.m[9] = -s;
  1477. result.m[6] = s;
  1478. result.m[1] = 0;
  1479. result.m[2] = 0;
  1480. result.m[3] = 0;
  1481. result.m[4] = 0;
  1482. result.m[7] = 0;
  1483. result.m[8] = 0;
  1484. result.m[11] = 0;
  1485. result.m[12] = 0;
  1486. result.m[13] = 0;
  1487. result.m[14] = 0;
  1488. };
  1489. Matrix.RotationY = function (angle) {
  1490. var result = new Matrix();
  1491. Matrix.RotationYToRef(angle, result);
  1492. return result;
  1493. };
  1494. Matrix.RotationYToRef = function (angle, result) {
  1495. var s = Math.sin(angle);
  1496. var c = Math.cos(angle);
  1497. result.m[5] = 1.0;
  1498. result.m[15] = 1.0;
  1499. result.m[0] = c;
  1500. result.m[2] = -s;
  1501. result.m[8] = s;
  1502. result.m[10] = c;
  1503. result.m[1] = 0;
  1504. result.m[3] = 0;
  1505. result.m[4] = 0;
  1506. result.m[6] = 0;
  1507. result.m[7] = 0;
  1508. result.m[9] = 0;
  1509. result.m[11] = 0;
  1510. result.m[12] = 0;
  1511. result.m[13] = 0;
  1512. result.m[14] = 0;
  1513. };
  1514. Matrix.RotationZ = function (angle) {
  1515. var result = new Matrix();
  1516. Matrix.RotationZToRef(angle, result);
  1517. return result;
  1518. };
  1519. Matrix.RotationZToRef = function (angle, result) {
  1520. var s = Math.sin(angle);
  1521. var c = Math.cos(angle);
  1522. result.m[10] = 1.0;
  1523. result.m[15] = 1.0;
  1524. result.m[0] = c;
  1525. result.m[1] = s;
  1526. result.m[4] = -s;
  1527. result.m[5] = c;
  1528. result.m[2] = 0;
  1529. result.m[3] = 0;
  1530. result.m[6] = 0;
  1531. result.m[7] = 0;
  1532. result.m[8] = 0;
  1533. result.m[9] = 0;
  1534. result.m[11] = 0;
  1535. result.m[12] = 0;
  1536. result.m[13] = 0;
  1537. result.m[14] = 0;
  1538. };
  1539. Matrix.RotationAxis = function (axis, angle) {
  1540. var s = Math.sin(-angle);
  1541. var c = Math.cos(-angle);
  1542. var c1 = 1 - c;
  1543. axis.normalize();
  1544. var result = Matrix.Zero();
  1545. result.m[0] = (axis.x * axis.x) * c1 + c;
  1546. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1547. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1548. result.m[3] = 0.0;
  1549. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1550. result.m[5] = (axis.y * axis.y) * c1 + c;
  1551. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1552. result.m[7] = 0.0;
  1553. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1554. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1555. result.m[10] = (axis.z * axis.z) * c1 + c;
  1556. result.m[11] = 0.0;
  1557. result.m[15] = 1.0;
  1558. return result;
  1559. };
  1560. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1561. var result = new Matrix();
  1562. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1563. return result;
  1564. };
  1565. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1566. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1567. this._tempQuaternion.toRotationMatrix(result);
  1568. };
  1569. Matrix.Scaling = function (x, y, z) {
  1570. var result = Matrix.Zero();
  1571. Matrix.ScalingToRef(x, y, z, result);
  1572. return result;
  1573. };
  1574. Matrix.ScalingToRef = function (x, y, z, result) {
  1575. result.m[0] = x;
  1576. result.m[1] = 0;
  1577. result.m[2] = 0;
  1578. result.m[3] = 0;
  1579. result.m[4] = 0;
  1580. result.m[5] = y;
  1581. result.m[6] = 0;
  1582. result.m[7] = 0;
  1583. result.m[8] = 0;
  1584. result.m[9] = 0;
  1585. result.m[10] = z;
  1586. result.m[11] = 0;
  1587. result.m[12] = 0;
  1588. result.m[13] = 0;
  1589. result.m[14] = 0;
  1590. result.m[15] = 1.0;
  1591. };
  1592. Matrix.Translation = function (x, y, z) {
  1593. var result = Matrix.Identity();
  1594. Matrix.TranslationToRef(x, y, z, result);
  1595. return result;
  1596. };
  1597. Matrix.TranslationToRef = function (x, y, z, result) {
  1598. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1599. };
  1600. Matrix.LookAtLH = function (eye, target, up) {
  1601. var result = Matrix.Zero();
  1602. Matrix.LookAtLHToRef(eye, target, up, result);
  1603. return result;
  1604. };
  1605. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1606. // Z axis
  1607. target.subtractToRef(eye, this._zAxis);
  1608. this._zAxis.normalize();
  1609. // X axis
  1610. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1611. this._xAxis.normalize();
  1612. // Y axis
  1613. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1614. this._yAxis.normalize();
  1615. // Eye angles
  1616. var ex = -Vector3.Dot(this._xAxis, eye);
  1617. var ey = -Vector3.Dot(this._yAxis, eye);
  1618. var ez = -Vector3.Dot(this._zAxis, eye);
  1619. 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);
  1620. };
  1621. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1622. var hw = 2.0 / width;
  1623. var hh = 2.0 / height;
  1624. var id = 1.0 / (zfar - znear);
  1625. var nid = znear / (znear - zfar);
  1626. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1627. };
  1628. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1629. var matrix = Matrix.Zero();
  1630. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1631. return matrix;
  1632. };
  1633. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1634. result.m[0] = 2.0 / (right - left);
  1635. result.m[1] = result.m[2] = result.m[3] = 0;
  1636. result.m[5] = 2.0 / (top - bottom);
  1637. result.m[4] = result.m[6] = result.m[7] = 0;
  1638. result.m[10] = -1.0 / (znear - zfar);
  1639. result.m[8] = result.m[9] = result.m[11] = 0;
  1640. result.m[12] = (left + right) / (left - right);
  1641. result.m[13] = (top + bottom) / (bottom - top);
  1642. result.m[14] = znear / (znear - zfar);
  1643. result.m[15] = 1.0;
  1644. };
  1645. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1646. var matrix = Matrix.Zero();
  1647. matrix.m[0] = (2.0 * znear) / width;
  1648. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1649. matrix.m[5] = (2.0 * znear) / height;
  1650. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1651. matrix.m[10] = -zfar / (znear - zfar);
  1652. matrix.m[8] = matrix.m[9] = 0.0;
  1653. matrix.m[11] = 1.0;
  1654. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1655. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1656. return matrix;
  1657. };
  1658. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1659. var matrix = Matrix.Zero();
  1660. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1661. return matrix;
  1662. };
  1663. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1664. var tan = 1.0 / (Math.tan(fov * 0.5));
  1665. result.m[0] = tan / aspect;
  1666. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1667. result.m[5] = tan;
  1668. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1669. result.m[8] = result.m[9] = 0.0;
  1670. result.m[10] = -zfar / (znear - zfar);
  1671. result.m[11] = 1.0;
  1672. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1673. result.m[14] = (znear * zfar) / (znear - zfar);
  1674. };
  1675. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1676. var cw = viewport.width;
  1677. var ch = viewport.height;
  1678. var cx = viewport.x;
  1679. var cy = viewport.y;
  1680. 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);
  1681. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1682. };
  1683. Matrix.Transpose = function (matrix) {
  1684. var result = new Matrix();
  1685. result.m[0] = matrix.m[0];
  1686. result.m[1] = matrix.m[4];
  1687. result.m[2] = matrix.m[8];
  1688. result.m[3] = matrix.m[12];
  1689. result.m[4] = matrix.m[1];
  1690. result.m[5] = matrix.m[5];
  1691. result.m[6] = matrix.m[9];
  1692. result.m[7] = matrix.m[13];
  1693. result.m[8] = matrix.m[2];
  1694. result.m[9] = matrix.m[6];
  1695. result.m[10] = matrix.m[10];
  1696. result.m[11] = matrix.m[14];
  1697. result.m[12] = matrix.m[3];
  1698. result.m[13] = matrix.m[7];
  1699. result.m[14] = matrix.m[11];
  1700. result.m[15] = matrix.m[15];
  1701. return result;
  1702. };
  1703. Matrix.Reflection = function (plane) {
  1704. var matrix = new Matrix();
  1705. Matrix.ReflectionToRef(plane, matrix);
  1706. return matrix;
  1707. };
  1708. Matrix.ReflectionToRef = function (plane, result) {
  1709. plane.normalize();
  1710. var x = plane.normal.x;
  1711. var y = plane.normal.y;
  1712. var z = plane.normal.z;
  1713. var temp = -2 * x;
  1714. var temp2 = -2 * y;
  1715. var temp3 = -2 * z;
  1716. result.m[0] = (temp * x) + 1;
  1717. result.m[1] = temp2 * x;
  1718. result.m[2] = temp3 * x;
  1719. result.m[3] = 0.0;
  1720. result.m[4] = temp * y;
  1721. result.m[5] = (temp2 * y) + 1;
  1722. result.m[6] = temp3 * y;
  1723. result.m[7] = 0.0;
  1724. result.m[8] = temp * z;
  1725. result.m[9] = temp2 * z;
  1726. result.m[10] = (temp3 * z) + 1;
  1727. result.m[11] = 0.0;
  1728. result.m[12] = temp * plane.d;
  1729. result.m[13] = temp2 * plane.d;
  1730. result.m[14] = temp3 * plane.d;
  1731. result.m[15] = 1.0;
  1732. };
  1733. Matrix._tempQuaternion = new Quaternion();
  1734. Matrix._xAxis = Vector3.Zero();
  1735. Matrix._yAxis = Vector3.Zero();
  1736. Matrix._zAxis = Vector3.Zero();
  1737. return Matrix;
  1738. })();
  1739. BABYLON.Matrix = Matrix;
  1740. var Plane = (function () {
  1741. function Plane(a, b, c, d) {
  1742. this.normal = new Vector3(a, b, c);
  1743. this.d = d;
  1744. }
  1745. Plane.prototype.asArray = function () {
  1746. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1747. };
  1748. // Methods
  1749. Plane.prototype.clone = function () {
  1750. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1751. };
  1752. Plane.prototype.normalize = function () {
  1753. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1754. var magnitude = 0;
  1755. if (norm !== 0) {
  1756. magnitude = 1.0 / norm;
  1757. }
  1758. this.normal.x *= magnitude;
  1759. this.normal.y *= magnitude;
  1760. this.normal.z *= magnitude;
  1761. this.d *= magnitude;
  1762. };
  1763. Plane.prototype.transform = function (transformation) {
  1764. var transposedMatrix = Matrix.Transpose(transformation);
  1765. var x = this.normal.x;
  1766. var y = this.normal.y;
  1767. var z = this.normal.z;
  1768. var d = this.d;
  1769. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1770. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1771. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1772. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1773. return new Plane(normalX, normalY, normalZ, finalD);
  1774. };
  1775. Plane.prototype.dotCoordinate = function (point) {
  1776. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1777. };
  1778. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1779. var x1 = point2.x - point1.x;
  1780. var y1 = point2.y - point1.y;
  1781. var z1 = point2.z - point1.z;
  1782. var x2 = point3.x - point1.x;
  1783. var y2 = point3.y - point1.y;
  1784. var z2 = point3.z - point1.z;
  1785. var yz = (y1 * z2) - (z1 * y2);
  1786. var xz = (z1 * x2) - (x1 * z2);
  1787. var xy = (x1 * y2) - (y1 * x2);
  1788. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1789. var invPyth;
  1790. if (pyth !== 0) {
  1791. invPyth = 1.0 / pyth;
  1792. } else {
  1793. invPyth = 0;
  1794. }
  1795. this.normal.x = yz * invPyth;
  1796. this.normal.y = xz * invPyth;
  1797. this.normal.z = xy * invPyth;
  1798. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1799. };
  1800. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1801. var dot = Vector3.Dot(this.normal, direction);
  1802. return (dot <= epsilon);
  1803. };
  1804. Plane.prototype.signedDistanceTo = function (point) {
  1805. return Vector3.Dot(point, this.normal) + this.d;
  1806. };
  1807. // Statics
  1808. Plane.FromArray = function (array) {
  1809. return new Plane(array[0], array[1], array[2], array[3]);
  1810. };
  1811. Plane.FromPoints = function (point1, point2, point3) {
  1812. var result = new Plane(0, 0, 0, 0);
  1813. result.copyFromPoints(point1, point2, point3);
  1814. return result;
  1815. };
  1816. Plane.FromPositionAndNormal = function (origin, normal) {
  1817. var result = new Plane(0, 0, 0, 0);
  1818. normal.normalize();
  1819. result.normal = normal;
  1820. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1821. return result;
  1822. };
  1823. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1824. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1825. return Vector3.Dot(point, normal) + d;
  1826. };
  1827. return Plane;
  1828. })();
  1829. BABYLON.Plane = Plane;
  1830. var Viewport = (function () {
  1831. function Viewport(x, y, width, height) {
  1832. this.x = x;
  1833. this.y = y;
  1834. this.width = width;
  1835. this.height = height;
  1836. }
  1837. Viewport.prototype.toGlobal = function (engine) {
  1838. var width = engine.getRenderWidth();
  1839. var height = engine.getRenderHeight();
  1840. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1841. };
  1842. return Viewport;
  1843. })();
  1844. BABYLON.Viewport = Viewport;
  1845. var Frustum = (function () {
  1846. function Frustum() {
  1847. }
  1848. Frustum.GetPlanes = function (transform) {
  1849. var frustumPlanes = [];
  1850. for (var index = 0; index < 6; index++) {
  1851. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1852. }
  1853. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1854. return frustumPlanes;
  1855. };
  1856. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1857. // Near
  1858. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1859. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1860. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1861. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1862. frustumPlanes[0].normalize();
  1863. // Far
  1864. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1865. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1866. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1867. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1868. frustumPlanes[1].normalize();
  1869. // Left
  1870. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1871. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1872. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1873. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1874. frustumPlanes[2].normalize();
  1875. // Right
  1876. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1877. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1878. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1879. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1880. frustumPlanes[3].normalize();
  1881. // Top
  1882. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1883. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1884. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1885. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1886. frustumPlanes[4].normalize();
  1887. // Bottom
  1888. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1889. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1890. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1891. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1892. frustumPlanes[5].normalize();
  1893. };
  1894. return Frustum;
  1895. })();
  1896. BABYLON.Frustum = Frustum;
  1897. var Ray = (function () {
  1898. function Ray(origin, direction, length) {
  1899. if (typeof length === "undefined") { length = Number.MAX_VALUE; }
  1900. this.origin = origin;
  1901. this.direction = direction;
  1902. this.length = length;
  1903. }
  1904. // Methods
  1905. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1906. var d = 0.0;
  1907. var maxValue = Number.MAX_VALUE;
  1908. if (Math.abs(this.direction.x) < 0.0000001) {
  1909. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1910. return false;
  1911. }
  1912. } else {
  1913. var inv = 1.0 / this.direction.x;
  1914. var min = (minimum.x - this.origin.x) * inv;
  1915. var max = (maximum.x - this.origin.x) * inv;
  1916. if (max === -Infinity) {
  1917. max = Infinity;
  1918. }
  1919. if (min > max) {
  1920. var temp = min;
  1921. min = max;
  1922. max = temp;
  1923. }
  1924. d = Math.max(min, d);
  1925. maxValue = Math.min(max, maxValue);
  1926. if (d > maxValue) {
  1927. return false;
  1928. }
  1929. }
  1930. if (Math.abs(this.direction.y) < 0.0000001) {
  1931. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1932. return false;
  1933. }
  1934. } else {
  1935. inv = 1.0 / this.direction.y;
  1936. min = (minimum.y - this.origin.y) * inv;
  1937. max = (maximum.y - this.origin.y) * inv;
  1938. if (max === -Infinity) {
  1939. max = Infinity;
  1940. }
  1941. if (min > max) {
  1942. temp = min;
  1943. min = max;
  1944. max = temp;
  1945. }
  1946. d = Math.max(min, d);
  1947. maxValue = Math.min(max, maxValue);
  1948. if (d > maxValue) {
  1949. return false;
  1950. }
  1951. }
  1952. if (Math.abs(this.direction.z) < 0.0000001) {
  1953. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1954. return false;
  1955. }
  1956. } else {
  1957. inv = 1.0 / this.direction.z;
  1958. min = (minimum.z - this.origin.z) * inv;
  1959. max = (maximum.z - this.origin.z) * inv;
  1960. if (max === -Infinity) {
  1961. max = Infinity;
  1962. }
  1963. if (min > max) {
  1964. temp = min;
  1965. min = max;
  1966. max = temp;
  1967. }
  1968. d = Math.max(min, d);
  1969. maxValue = Math.min(max, maxValue);
  1970. if (d > maxValue) {
  1971. return false;
  1972. }
  1973. }
  1974. return true;
  1975. };
  1976. Ray.prototype.intersectsBox = function (box) {
  1977. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1978. };
  1979. Ray.prototype.intersectsSphere = function (sphere) {
  1980. var x = sphere.center.x - this.origin.x;
  1981. var y = sphere.center.y - this.origin.y;
  1982. var z = sphere.center.z - this.origin.z;
  1983. var pyth = (x * x) + (y * y) + (z * z);
  1984. var rr = sphere.radius * sphere.radius;
  1985. if (pyth <= rr) {
  1986. return true;
  1987. }
  1988. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1989. if (dot < 0.0) {
  1990. return false;
  1991. }
  1992. var temp = pyth - (dot * dot);
  1993. return temp <= rr;
  1994. };
  1995. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1996. if (!this._edge1) {
  1997. this._edge1 = Vector3.Zero();
  1998. this._edge2 = Vector3.Zero();
  1999. this._pvec = Vector3.Zero();
  2000. this._tvec = Vector3.Zero();
  2001. this._qvec = Vector3.Zero();
  2002. }
  2003. vertex1.subtractToRef(vertex0, this._edge1);
  2004. vertex2.subtractToRef(vertex0, this._edge2);
  2005. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2006. var det = Vector3.Dot(this._edge1, this._pvec);
  2007. if (det === 0) {
  2008. return null;
  2009. }
  2010. var invdet = 1 / det;
  2011. this.origin.subtractToRef(vertex0, this._tvec);
  2012. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2013. if (bu < 0 || bu > 1.0) {
  2014. return null;
  2015. }
  2016. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2017. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2018. if (bv < 0 || bu + bv > 1.0) {
  2019. return null;
  2020. }
  2021. //check if the distance is longer than the predefined length.
  2022. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2023. if (distance > this.length) {
  2024. return null;
  2025. }
  2026. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2027. };
  2028. // Statics
  2029. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2030. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2031. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2032. var direction = end.subtract(start);
  2033. direction.normalize();
  2034. return new Ray(start, direction);
  2035. };
  2036. /**
  2037. * 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
  2038. * transformed to the given world matrix.
  2039. * @param origin The origin point
  2040. * @param end The end point
  2041. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2042. */
  2043. Ray.CreateNewFromTo = function (origin, end, world) {
  2044. if (typeof world === "undefined") { world = Matrix.Identity(); }
  2045. var direction = end.subtract(origin);
  2046. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2047. direction.normalize();
  2048. return Ray.Transform(new Ray(origin, direction, length), world);
  2049. };
  2050. Ray.Transform = function (ray, matrix) {
  2051. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2052. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2053. return new Ray(newOrigin, newDirection, ray.length);
  2054. };
  2055. return Ray;
  2056. })();
  2057. BABYLON.Ray = Ray;
  2058. (function (Space) {
  2059. Space[Space["LOCAL"] = 0] = "LOCAL";
  2060. Space[Space["WORLD"] = 1] = "WORLD";
  2061. })(BABYLON.Space || (BABYLON.Space = {}));
  2062. var Space = BABYLON.Space;
  2063. var Axis = (function () {
  2064. function Axis() {
  2065. }
  2066. Axis.X = new Vector3(1, 0, 0);
  2067. Axis.Y = new Vector3(0, 1, 0);
  2068. Axis.Z = new Vector3(0, 0, 1);
  2069. return Axis;
  2070. })();
  2071. BABYLON.Axis = Axis;
  2072. ;
  2073. var BezierCurve = (function () {
  2074. function BezierCurve() {
  2075. }
  2076. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2077. // Extract X (which is equal to time here)
  2078. var f0 = 1 - 3 * x2 + 3 * x1;
  2079. var f1 = 3 * x2 - 6 * x1;
  2080. var f2 = 3 * x1;
  2081. var refinedT = t;
  2082. for (var i = 0; i < 5; i++) {
  2083. var refinedT2 = refinedT * refinedT;
  2084. var refinedT3 = refinedT2 * refinedT;
  2085. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2086. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2087. refinedT -= (x - t) * slope;
  2088. refinedT = Math.min(1, Math.max(0, refinedT));
  2089. }
  2090. // Resolve cubic bezier for the given x
  2091. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2092. };
  2093. return BezierCurve;
  2094. })();
  2095. BABYLON.BezierCurve = BezierCurve;
  2096. (function (Orientation) {
  2097. Orientation[Orientation["CW"] = 0] = "CW";
  2098. Orientation[Orientation["CCW"] = 1] = "CCW";
  2099. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2100. var Orientation = BABYLON.Orientation;
  2101. var Angle = (function () {
  2102. function Angle(radians) {
  2103. var _this = this;
  2104. this.degrees = function () {
  2105. return _this._radians * 180 / Math.PI;
  2106. };
  2107. this.radians = function () {
  2108. return _this._radians;
  2109. };
  2110. this._radians = radians;
  2111. if (this._radians < 0)
  2112. this._radians += (2 * Math.PI);
  2113. }
  2114. Angle.BetweenTwoPoints = function (a, b) {
  2115. var delta = b.subtract(a);
  2116. var theta = Math.atan2(delta.y, delta.x);
  2117. return new Angle(theta);
  2118. };
  2119. Angle.FromRadians = function (radians) {
  2120. return new Angle(radians);
  2121. };
  2122. Angle.FromDegrees = function (degrees) {
  2123. return new Angle(degrees * Math.PI / 180);
  2124. };
  2125. return Angle;
  2126. })();
  2127. BABYLON.Angle = Angle;
  2128. var Arc2 = (function () {
  2129. function Arc2(startPoint, midPoint, endPoint) {
  2130. this.startPoint = startPoint;
  2131. this.midPoint = midPoint;
  2132. this.endPoint = endPoint;
  2133. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2134. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2135. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2136. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2137. 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);
  2138. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2139. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2140. var a1 = this.startAngle.degrees();
  2141. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2142. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2143. // angles correction
  2144. if (a2 - a1 > +180.0)
  2145. a2 -= 360.0;
  2146. if (a2 - a1 < -180.0)
  2147. a2 += 360.0;
  2148. if (a3 - a2 > +180.0)
  2149. a3 -= 360.0;
  2150. if (a3 - a2 < -180.0)
  2151. a3 += 360.0;
  2152. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2153. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2154. }
  2155. return Arc2;
  2156. })();
  2157. BABYLON.Arc2 = Arc2;
  2158. var PathCursor = (function () {
  2159. function PathCursor(path) {
  2160. this.path = path;
  2161. this._onchange = new Array();
  2162. this.value = 0;
  2163. this.animations = new Array();
  2164. }
  2165. PathCursor.prototype.getPoint = function () {
  2166. var point = this.path.getPointAtLengthPosition(this.value);
  2167. return new Vector3(point.x, 0, point.y);
  2168. };
  2169. PathCursor.prototype.moveAhead = function (step) {
  2170. if (typeof step === "undefined") { step = 0.002; }
  2171. this.move(step);
  2172. };
  2173. PathCursor.prototype.moveBack = function (step) {
  2174. if (typeof step === "undefined") { step = 0.002; }
  2175. this.move(-step);
  2176. };
  2177. PathCursor.prototype.move = function (step) {
  2178. if (Math.abs(step) > 1) {
  2179. throw "step size should be less than 1.";
  2180. }
  2181. this.value += step;
  2182. this.ensureLimits();
  2183. this.raiseOnChange();
  2184. };
  2185. PathCursor.prototype.ensureLimits = function () {
  2186. while (this.value > 1) {
  2187. this.value -= 1;
  2188. }
  2189. while (this.value < 0) {
  2190. this.value += 1;
  2191. }
  2192. };
  2193. // used by animation engine
  2194. PathCursor.prototype.markAsDirty = function (propertyName) {
  2195. this.ensureLimits();
  2196. this.raiseOnChange();
  2197. };
  2198. PathCursor.prototype.raiseOnChange = function () {
  2199. var _this = this;
  2200. this._onchange.forEach(function (f) {
  2201. return f(_this);
  2202. });
  2203. };
  2204. PathCursor.prototype.onchange = function (f) {
  2205. this._onchange.push(f);
  2206. };
  2207. return PathCursor;
  2208. })();
  2209. BABYLON.PathCursor = PathCursor;
  2210. var Path2 = (function () {
  2211. function Path2(x, y) {
  2212. this._points = [];
  2213. this._length = 0;
  2214. this.closed = false;
  2215. this._points.push(new Vector2(x, y));
  2216. }
  2217. Path2.prototype.addLineTo = function (x, y) {
  2218. if (closed) {
  2219. BABYLON.Tools.Error("cannot add lines to closed paths");
  2220. return this;
  2221. }
  2222. var newPoint = new Vector2(x, y);
  2223. var previousPoint = this._points[this._points.length - 1];
  2224. this._points.push(newPoint);
  2225. this._length += newPoint.subtract(previousPoint).length();
  2226. return this;
  2227. };
  2228. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2229. if (typeof numberOfSegments === "undefined") { numberOfSegments = 36; }
  2230. if (closed) {
  2231. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2232. return this;
  2233. }
  2234. var startPoint = this._points[this._points.length - 1];
  2235. var midPoint = new Vector2(midX, midY);
  2236. var endPoint = new Vector2(endX, endY);
  2237. var arc = new Arc2(startPoint, midPoint, endPoint);
  2238. var increment = arc.angle.radians() / numberOfSegments;
  2239. if (arc.orientation === 0 /* CW */)
  2240. increment *= -1;
  2241. var currentAngle = arc.startAngle.radians() + increment;
  2242. for (var i = 0; i < numberOfSegments; i++) {
  2243. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2244. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2245. this.addLineTo(x, y);
  2246. currentAngle += increment;
  2247. }
  2248. return this;
  2249. };
  2250. Path2.prototype.close = function () {
  2251. this.closed = true;
  2252. return this;
  2253. };
  2254. Path2.prototype.length = function () {
  2255. var result = this._length;
  2256. if (!this.closed) {
  2257. var lastPoint = this._points[this._points.length - 1];
  2258. var firstPoint = this._points[0];
  2259. result += (firstPoint.subtract(lastPoint).length());
  2260. }
  2261. return result;
  2262. };
  2263. Path2.prototype.getPoints = function () {
  2264. return this._points;
  2265. };
  2266. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2267. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2268. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2269. return;
  2270. }
  2271. var lengthPosition = normalizedLengthPosition * this.length();
  2272. var previousOffset = 0;
  2273. for (var i = 0; i < this._points.length; i++) {
  2274. var j = (i + 1) % this._points.length;
  2275. var a = this._points[i];
  2276. var b = this._points[j];
  2277. var bToA = b.subtract(a);
  2278. var nextOffset = (bToA.length() + previousOffset);
  2279. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2280. var dir = bToA.normalize();
  2281. var localOffset = lengthPosition - previousOffset;
  2282. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2283. }
  2284. previousOffset = nextOffset;
  2285. }
  2286. BABYLON.Tools.Error("internal error");
  2287. };
  2288. Path2.StartingAt = function (x, y) {
  2289. return new Path2(x, y);
  2290. };
  2291. return Path2;
  2292. })();
  2293. BABYLON.Path2 = Path2;
  2294. })(BABYLON || (BABYLON = {}));
  2295. //# sourceMappingURL=babylon.math.js.map
  2296. var BABYLON;
  2297. (function (BABYLON) {
  2298. // Screenshots
  2299. var screenshotCanvas;
  2300. var cloneValue = function (source, destinationObject) {
  2301. if (!source)
  2302. return null;
  2303. if (source instanceof BABYLON.Mesh) {
  2304. return null;
  2305. }
  2306. if (source instanceof BABYLON.SubMesh) {
  2307. return source.clone(destinationObject);
  2308. } else if (source.clone) {
  2309. return source.clone();
  2310. }
  2311. return null;
  2312. };
  2313. var Tools = (function () {
  2314. function Tools() {
  2315. }
  2316. Tools.GetFilename = function (path) {
  2317. var index = path.lastIndexOf("/");
  2318. if (index < 0)
  2319. return path;
  2320. return path.substring(index + 1);
  2321. };
  2322. Tools.GetDOMTextContent = function (element) {
  2323. var result = "";
  2324. var child = element.firstChild;
  2325. while (child) {
  2326. if (child.nodeType == 3) {
  2327. result += child.textContent;
  2328. }
  2329. child = child.nextSibling;
  2330. }
  2331. return result;
  2332. };
  2333. Tools.ToDegrees = function (angle) {
  2334. return angle * 180 / Math.PI;
  2335. };
  2336. Tools.ToRadians = function (angle) {
  2337. return angle * Math.PI / 180;
  2338. };
  2339. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2340. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2341. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2342. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2343. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2344. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2345. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2346. }
  2347. return {
  2348. minimum: minimum,
  2349. maximum: maximum
  2350. };
  2351. };
  2352. Tools.ExtractMinAndMax = function (positions, start, count) {
  2353. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2354. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2355. for (var index = start; index < start + count; index++) {
  2356. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2357. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2358. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2359. }
  2360. return {
  2361. minimum: minimum,
  2362. maximum: maximum
  2363. };
  2364. };
  2365. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2366. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2367. return undefined;
  2368. return Array.isArray(obj) ? obj : [obj];
  2369. };
  2370. // Misc.
  2371. Tools.GetPointerPrefix = function () {
  2372. var eventPrefix = "pointer";
  2373. // Check if hand.js is referenced or if the browser natively supports pointer events
  2374. if (!navigator.pointerEnabled) {
  2375. eventPrefix = "mouse";
  2376. }
  2377. return eventPrefix;
  2378. };
  2379. Tools.QueueNewFrame = function (func) {
  2380. if (window.requestAnimationFrame)
  2381. window.requestAnimationFrame(func);
  2382. else if (window.msRequestAnimationFrame)
  2383. window.msRequestAnimationFrame(func);
  2384. else if (window.webkitRequestAnimationFrame)
  2385. window.webkitRequestAnimationFrame(func);
  2386. else if (window.mozRequestAnimationFrame)
  2387. window.mozRequestAnimationFrame(func);
  2388. else if (window.oRequestAnimationFrame)
  2389. window.oRequestAnimationFrame(func);
  2390. else {
  2391. window.setTimeout(func, 16);
  2392. }
  2393. };
  2394. Tools.RequestFullscreen = function (element) {
  2395. if (element.requestFullscreen)
  2396. element.requestFullscreen();
  2397. else if (element.msRequestFullscreen)
  2398. element.msRequestFullscreen();
  2399. else if (element.webkitRequestFullscreen)
  2400. element.webkitRequestFullscreen();
  2401. else if (element.mozRequestFullScreen)
  2402. element.mozRequestFullScreen();
  2403. };
  2404. Tools.ExitFullscreen = function () {
  2405. if (document.exitFullscreen) {
  2406. document.exitFullscreen();
  2407. } else if (document.mozCancelFullScreen) {
  2408. document.mozCancelFullScreen();
  2409. } else if (document.webkitCancelFullScreen) {
  2410. document.webkitCancelFullScreen();
  2411. } else if (document.msCancelFullScreen) {
  2412. document.msCancelFullScreen();
  2413. }
  2414. };
  2415. // External files
  2416. Tools.CleanUrl = function (url) {
  2417. url = url.replace(/#/mg, "%23");
  2418. return url;
  2419. };
  2420. Tools.LoadImage = function (url, onload, onerror, database) {
  2421. url = Tools.CleanUrl(url);
  2422. var img = new Image();
  2423. if (url.substr(0, 5) != "data:")
  2424. img.crossOrigin = 'anonymous';
  2425. img.onload = function () {
  2426. onload(img);
  2427. };
  2428. img.onerror = function (err) {
  2429. onerror(img, err);
  2430. };
  2431. var noIndexedDB = function () {
  2432. img.src = url;
  2433. };
  2434. var loadFromIndexedDB = function () {
  2435. database.loadImageFromDB(url, img);
  2436. };
  2437. //ANY database to do!
  2438. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2439. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2440. } else {
  2441. if (url.indexOf("file:") === -1) {
  2442. noIndexedDB();
  2443. } else {
  2444. try {
  2445. var textureName = url.substring(5);
  2446. var blobURL;
  2447. try {
  2448. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2449. } catch (ex) {
  2450. // Chrome doesn't support oneTimeOnly parameter
  2451. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2452. }
  2453. img.src = blobURL;
  2454. } catch (e) {
  2455. Tools.Log("Error while trying to load texture: " + textureName);
  2456. img.src = null;
  2457. }
  2458. }
  2459. }
  2460. return img;
  2461. };
  2462. //ANY
  2463. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2464. url = Tools.CleanUrl(url);
  2465. var noIndexedDB = function () {
  2466. var request = new XMLHttpRequest();
  2467. var loadUrl = Tools.BaseUrl + url;
  2468. request.open('GET', loadUrl, true);
  2469. if (useArrayBuffer) {
  2470. request.responseType = "arraybuffer";
  2471. }
  2472. request.onprogress = progressCallBack;
  2473. request.onreadystatechange = function () {
  2474. if (request.readyState == 4) {
  2475. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2476. callback(!useArrayBuffer ? request.responseText : request.response);
  2477. } else {
  2478. if (onError) {
  2479. onError();
  2480. } else {
  2481. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2482. }
  2483. }
  2484. }
  2485. };
  2486. request.send(null);
  2487. };
  2488. var loadFromIndexedDB = function () {
  2489. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2490. };
  2491. if (url.indexOf("file:") !== -1) {
  2492. var fileName = url.substring(5);
  2493. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2494. } else {
  2495. // Caching all files
  2496. if (database && database.enableSceneOffline) {
  2497. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2498. } else {
  2499. noIndexedDB();
  2500. }
  2501. }
  2502. };
  2503. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2504. var reader = new FileReader();
  2505. reader.onload = function (e) {
  2506. callback(e.target.result);
  2507. };
  2508. reader.onprogress = progressCallback;
  2509. reader.readAsDataURL(fileToLoad);
  2510. };
  2511. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2512. var reader = new FileReader();
  2513. reader.onload = function (e) {
  2514. callback(e.target.result);
  2515. };
  2516. reader.onprogress = progressCallBack;
  2517. if (!useArrayBuffer) {
  2518. // Asynchronous read
  2519. reader.readAsText(fileToLoad);
  2520. } else {
  2521. reader.readAsArrayBuffer(fileToLoad);
  2522. }
  2523. };
  2524. // Misc.
  2525. Tools.Clamp = function (value, min, max) {
  2526. if (typeof min === "undefined") { min = 0; }
  2527. if (typeof max === "undefined") { max = 1; }
  2528. return Math.min(max, Math.max(min, value));
  2529. };
  2530. // Returns -1 when value is a negative number and
  2531. // +1 when value is a positive number.
  2532. Tools.Sign = function (value) {
  2533. value = +value; // convert to a number
  2534. if (value === 0 || isNaN(value))
  2535. return value;
  2536. return value > 0 ? 1 : -1;
  2537. };
  2538. Tools.Format = function (value, decimals) {
  2539. if (typeof decimals === "undefined") { decimals = 2; }
  2540. return value.toFixed(decimals);
  2541. };
  2542. Tools.CheckExtends = function (v, min, max) {
  2543. if (v.x < min.x)
  2544. min.x = v.x;
  2545. if (v.y < min.y)
  2546. min.y = v.y;
  2547. if (v.z < min.z)
  2548. min.z = v.z;
  2549. if (v.x > max.x)
  2550. max.x = v.x;
  2551. if (v.y > max.y)
  2552. max.y = v.y;
  2553. if (v.z > max.z)
  2554. max.z = v.z;
  2555. };
  2556. Tools.WithinEpsilon = function (a, b, epsilon) {
  2557. if (typeof epsilon === "undefined") { epsilon = 1.401298E-45; }
  2558. var num = a - b;
  2559. return -epsilon <= num && num <= epsilon;
  2560. };
  2561. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2562. for (var prop in source) {
  2563. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2564. continue;
  2565. }
  2566. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2567. continue;
  2568. }
  2569. var sourceValue = source[prop];
  2570. var typeOfSourceValue = typeof sourceValue;
  2571. if (typeOfSourceValue == "function") {
  2572. continue;
  2573. }
  2574. if (typeOfSourceValue == "object") {
  2575. if (sourceValue instanceof Array) {
  2576. destination[prop] = [];
  2577. if (sourceValue.length > 0) {
  2578. if (typeof sourceValue[0] == "object") {
  2579. for (var index = 0; index < sourceValue.length; index++) {
  2580. var clonedValue = cloneValue(sourceValue[index], destination);
  2581. if (destination[prop].indexOf(clonedValue) === -1) {
  2582. destination[prop].push(clonedValue);
  2583. }
  2584. }
  2585. } else {
  2586. destination[prop] = sourceValue.slice(0);
  2587. }
  2588. }
  2589. } else {
  2590. destination[prop] = cloneValue(sourceValue, destination);
  2591. }
  2592. } else {
  2593. destination[prop] = sourceValue;
  2594. }
  2595. }
  2596. };
  2597. Tools.IsEmpty = function (obj) {
  2598. for (var i in obj) {
  2599. return false;
  2600. }
  2601. return true;
  2602. };
  2603. Tools.RegisterTopRootEvents = function (events) {
  2604. for (var index = 0; index < events.length; index++) {
  2605. var event = events[index];
  2606. window.addEventListener(event.name, event.handler, false);
  2607. try {
  2608. if (window.parent) {
  2609. window.parent.addEventListener(event.name, event.handler, false);
  2610. }
  2611. } catch (e) {
  2612. // Silently fails...
  2613. }
  2614. }
  2615. };
  2616. Tools.UnregisterTopRootEvents = function (events) {
  2617. for (var index = 0; index < events.length; index++) {
  2618. var event = events[index];
  2619. window.removeEventListener(event.name, event.handler);
  2620. try {
  2621. if (window.parent) {
  2622. window.parent.removeEventListener(event.name, event.handler);
  2623. }
  2624. } catch (e) {
  2625. // Silently fails...
  2626. }
  2627. }
  2628. };
  2629. Tools.CreateScreenshot = function (engine, camera, size) {
  2630. var width;
  2631. var height;
  2632. var scene = camera.getScene();
  2633. var previousCamera = null;
  2634. if (scene.activeCamera !== camera) {
  2635. previousCamera = scene.activeCamera;
  2636. scene.activeCamera = camera;
  2637. }
  2638. //If a precision value is specified
  2639. if (size.precision) {
  2640. width = Math.round(engine.getRenderWidth() * size.precision);
  2641. height = Math.round(width / engine.getAspectRatio(camera));
  2642. size = { width: width, height: height };
  2643. } else if (size.width && size.height) {
  2644. width = size.width;
  2645. height = size.height;
  2646. } else if (size.width && !size.height) {
  2647. width = size.width;
  2648. height = Math.round(width / engine.getAspectRatio(camera));
  2649. size = { width: width, height: height };
  2650. } else if (size.height && !size.width) {
  2651. height = size.height;
  2652. width = Math.round(height * engine.getAspectRatio(camera));
  2653. size = { width: width, height: height };
  2654. } else if (!isNaN(size)) {
  2655. height = size;
  2656. width = size;
  2657. } else {
  2658. Tools.Error("Invalid 'size' parameter !");
  2659. return;
  2660. }
  2661. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2662. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2663. texture.renderList = scene.meshes;
  2664. texture.onAfterRender = function () {
  2665. // Read the contents of the framebuffer
  2666. var numberOfChannelsByLine = width * 4;
  2667. var halfHeight = height / 2;
  2668. //Reading datas from WebGL
  2669. var data = engine.readPixels(0, 0, width, height);
  2670. for (var i = 0; i < halfHeight; i++) {
  2671. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2672. var currentCell = j + i * numberOfChannelsByLine;
  2673. var targetLine = height - i - 1;
  2674. var targetCell = j + targetLine * numberOfChannelsByLine;
  2675. var temp = data[currentCell];
  2676. data[currentCell] = data[targetCell];
  2677. data[targetCell] = temp;
  2678. }
  2679. }
  2680. // Create a 2D canvas to store the result
  2681. if (!screenshotCanvas) {
  2682. screenshotCanvas = document.createElement('canvas');
  2683. }
  2684. screenshotCanvas.width = width;
  2685. screenshotCanvas.height = height;
  2686. var context = screenshotCanvas.getContext('2d');
  2687. // Copy the pixels to a 2D canvas
  2688. var imageData = context.createImageData(width, height);
  2689. imageData.data.set(data);
  2690. context.putImageData(imageData, 0, 0);
  2691. var base64Image = screenshotCanvas.toDataURL();
  2692. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2693. if (("download" in document.createElement("a"))) {
  2694. var a = window.document.createElement("a");
  2695. a.href = base64Image;
  2696. var date = new Date();
  2697. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2698. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2699. window.document.body.appendChild(a);
  2700. a.addEventListener("click", function () {
  2701. a.parentElement.removeChild(a);
  2702. });
  2703. a.click();
  2704. //Or opening a new tab with the image if it is not possible to automatically start download.
  2705. } else {
  2706. var newWindow = window.open("");
  2707. var img = newWindow.document.createElement("img");
  2708. img.src = base64Image;
  2709. newWindow.document.body.appendChild(img);
  2710. }
  2711. };
  2712. texture.render(true);
  2713. texture.dispose();
  2714. if (previousCamera) {
  2715. scene.activeCamera = previousCamera;
  2716. }
  2717. };
  2718. // XHR response validator for local file scenario
  2719. Tools.ValidateXHRData = function (xhr, dataType) {
  2720. if (typeof dataType === "undefined") { dataType = 7; }
  2721. try {
  2722. if (dataType & 1) {
  2723. if (xhr.responseText && xhr.responseText.length > 0) {
  2724. return true;
  2725. } else if (dataType === 1) {
  2726. return false;
  2727. }
  2728. }
  2729. if (dataType & 2) {
  2730. // Check header width and height since there is no "TGA" magic number
  2731. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2732. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2733. return true;
  2734. } else if (dataType === 2) {
  2735. return false;
  2736. }
  2737. }
  2738. if (dataType & 4) {
  2739. // Check for the "DDS" magic number
  2740. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2741. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2742. return true;
  2743. } else {
  2744. return false;
  2745. }
  2746. }
  2747. } catch (e) {
  2748. // Global protection
  2749. }
  2750. return false;
  2751. };
  2752. Object.defineProperty(Tools, "NoneLogLevel", {
  2753. get: function () {
  2754. return Tools._NoneLogLevel;
  2755. },
  2756. enumerable: true,
  2757. configurable: true
  2758. });
  2759. Object.defineProperty(Tools, "MessageLogLevel", {
  2760. get: function () {
  2761. return Tools._MessageLogLevel;
  2762. },
  2763. enumerable: true,
  2764. configurable: true
  2765. });
  2766. Object.defineProperty(Tools, "WarningLogLevel", {
  2767. get: function () {
  2768. return Tools._WarningLogLevel;
  2769. },
  2770. enumerable: true,
  2771. configurable: true
  2772. });
  2773. Object.defineProperty(Tools, "ErrorLogLevel", {
  2774. get: function () {
  2775. return Tools._ErrorLogLevel;
  2776. },
  2777. enumerable: true,
  2778. configurable: true
  2779. });
  2780. Object.defineProperty(Tools, "AllLogLevel", {
  2781. get: function () {
  2782. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2783. },
  2784. enumerable: true,
  2785. configurable: true
  2786. });
  2787. Tools._AddLogEntry = function (entry) {
  2788. Tools._LogCache = entry + Tools._LogCache;
  2789. if (Tools.OnNewCacheEntry) {
  2790. Tools.OnNewCacheEntry(entry);
  2791. }
  2792. };
  2793. Tools._FormatMessage = function (message) {
  2794. var padStr = function (i) {
  2795. return (i < 10) ? "0" + i : "" + i;
  2796. };
  2797. var date = new Date();
  2798. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2799. };
  2800. Tools._LogDisabled = function (message) {
  2801. // nothing to do
  2802. };
  2803. Tools._LogEnabled = function (message) {
  2804. var formattedMessage = Tools._FormatMessage(message);
  2805. console.log("BJS - " + formattedMessage);
  2806. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2807. Tools._AddLogEntry(entry);
  2808. };
  2809. Tools._WarnDisabled = function (message) {
  2810. // nothing to do
  2811. };
  2812. Tools._WarnEnabled = function (message) {
  2813. var formattedMessage = Tools._FormatMessage(message);
  2814. console.warn("BJS - " + formattedMessage);
  2815. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2816. Tools._AddLogEntry(entry);
  2817. };
  2818. Tools._ErrorDisabled = function (message) {
  2819. // nothing to do
  2820. };
  2821. Tools._ErrorEnabled = function (message) {
  2822. var formattedMessage = Tools._FormatMessage(message);
  2823. console.error("BJS - " + formattedMessage);
  2824. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2825. Tools._AddLogEntry(entry);
  2826. };
  2827. Object.defineProperty(Tools, "LogCache", {
  2828. get: function () {
  2829. return Tools._LogCache;
  2830. },
  2831. enumerable: true,
  2832. configurable: true
  2833. });
  2834. Object.defineProperty(Tools, "LogLevels", {
  2835. set: function (level) {
  2836. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2837. Tools.Log = Tools._LogEnabled;
  2838. } else {
  2839. Tools.Log = Tools._LogDisabled;
  2840. }
  2841. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2842. Tools.Warn = Tools._WarnEnabled;
  2843. } else {
  2844. Tools.Warn = Tools._WarnDisabled;
  2845. }
  2846. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2847. Tools.Error = Tools._ErrorEnabled;
  2848. } else {
  2849. Tools.Error = Tools._ErrorDisabled;
  2850. }
  2851. },
  2852. enumerable: true,
  2853. configurable: true
  2854. });
  2855. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2856. get: function () {
  2857. return Tools._PerformanceNoneLogLevel;
  2858. },
  2859. enumerable: true,
  2860. configurable: true
  2861. });
  2862. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2863. get: function () {
  2864. return Tools._PerformanceUserMarkLogLevel;
  2865. },
  2866. enumerable: true,
  2867. configurable: true
  2868. });
  2869. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2870. get: function () {
  2871. return Tools._PerformanceConsoleLogLevel;
  2872. },
  2873. enumerable: true,
  2874. configurable: true
  2875. });
  2876. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2877. set: function (level) {
  2878. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2879. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2880. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2881. return;
  2882. }
  2883. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2884. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2885. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2886. return;
  2887. }
  2888. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2889. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2890. },
  2891. enumerable: true,
  2892. configurable: true
  2893. });
  2894. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2895. };
  2896. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2897. };
  2898. Tools._StartUserMark = function (counterName, condition) {
  2899. if (typeof condition === "undefined") { condition = true; }
  2900. if (!condition || !Tools._performance.mark) {
  2901. return;
  2902. }
  2903. Tools._performance.mark(counterName + "-Begin");
  2904. };
  2905. Tools._EndUserMark = function (counterName, condition) {
  2906. if (typeof condition === "undefined") { condition = true; }
  2907. if (!condition || !Tools._performance.mark) {
  2908. return;
  2909. }
  2910. Tools._performance.mark(counterName + "-End");
  2911. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2912. };
  2913. Tools._StartPerformanceConsole = function (counterName, condition) {
  2914. if (typeof condition === "undefined") { condition = true; }
  2915. if (!condition) {
  2916. return;
  2917. }
  2918. Tools._StartUserMark(counterName, condition);
  2919. if (console.time) {
  2920. console.time(counterName);
  2921. }
  2922. };
  2923. Tools._EndPerformanceConsole = function (counterName, condition) {
  2924. if (typeof condition === "undefined") { condition = true; }
  2925. if (!condition) {
  2926. return;
  2927. }
  2928. Tools._EndUserMark(counterName, condition);
  2929. if (console.time) {
  2930. console.timeEnd(counterName);
  2931. }
  2932. };
  2933. Object.defineProperty(Tools, "Now", {
  2934. get: function () {
  2935. if (window.performance && window.performance.now) {
  2936. return window.performance.now();
  2937. }
  2938. return new Date().getTime();
  2939. },
  2940. enumerable: true,
  2941. configurable: true
  2942. });
  2943. // Deprecated
  2944. Tools.GetFps = function () {
  2945. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2946. return 0;
  2947. };
  2948. Tools.BaseUrl = "";
  2949. Tools.GetExponantOfTwo = function (value, max) {
  2950. var count = 1;
  2951. do {
  2952. count *= 2;
  2953. } while(count < value);
  2954. if (count > max)
  2955. count = max;
  2956. return count;
  2957. };
  2958. Tools._NoneLogLevel = 0;
  2959. Tools._MessageLogLevel = 1;
  2960. Tools._WarningLogLevel = 2;
  2961. Tools._ErrorLogLevel = 4;
  2962. Tools._LogCache = "";
  2963. Tools.Log = Tools._LogEnabled;
  2964. Tools.Warn = Tools._WarnEnabled;
  2965. Tools.Error = Tools._ErrorEnabled;
  2966. Tools._PerformanceNoneLogLevel = 0;
  2967. Tools._PerformanceUserMarkLogLevel = 1;
  2968. Tools._PerformanceConsoleLogLevel = 2;
  2969. Tools._performance = window.performance;
  2970. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2971. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2972. return Tools;
  2973. })();
  2974. BABYLON.Tools = Tools;
  2975. /**
  2976. * An implementation of a loop for asynchronous functions.
  2977. */
  2978. var AsyncLoop = (function () {
  2979. /**
  2980. * Constroctor.
  2981. * @param iterations the number of iterations.
  2982. * @param _fn the function to run each iteration
  2983. * @param _successCallback the callback that will be called upon succesful execution
  2984. * @param offset starting offset.
  2985. */
  2986. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  2987. if (typeof offset === "undefined") { offset = 0; }
  2988. this.iterations = iterations;
  2989. this._fn = _fn;
  2990. this._successCallback = _successCallback;
  2991. this.index = offset - 1;
  2992. this._done = false;
  2993. }
  2994. /**
  2995. * Execute the next iteration. Must be called after the last iteration was finished.
  2996. */
  2997. AsyncLoop.prototype.executeNext = function () {
  2998. if (!this._done) {
  2999. if (this.index + 1 < this.iterations) {
  3000. ++this.index;
  3001. this._fn(this);
  3002. } else {
  3003. this.breakLoop();
  3004. }
  3005. }
  3006. };
  3007. /**
  3008. * Break the loop and run the success callback.
  3009. */
  3010. AsyncLoop.prototype.breakLoop = function () {
  3011. this._done = true;
  3012. this._successCallback();
  3013. };
  3014. /**
  3015. * Helper function
  3016. */
  3017. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3018. if (typeof offset === "undefined") { offset = 0; }
  3019. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3020. loop.executeNext();
  3021. return loop;
  3022. };
  3023. /**
  3024. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3025. * @param iterations total number of iterations
  3026. * @param syncedIterations number of synchronous iterations in each async iteration.
  3027. * @param fn the function to call each iteration.
  3028. * @param callback a success call back that will be called when iterating stops.
  3029. * @param breakFunction a break condition (optional)
  3030. * @param timeout timeout settings for the setTimeout function. default - 0.
  3031. * @constructor
  3032. */
  3033. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3034. if (typeof timeout === "undefined") { timeout = 0; }
  3035. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3036. if (breakFunction && breakFunction())
  3037. loop.breakLoop();
  3038. else {
  3039. setTimeout(function () {
  3040. for (var i = 0; i < syncedIterations; ++i) {
  3041. var iteration = (loop.index * syncedIterations) + i;
  3042. if (iteration >= iterations)
  3043. break;
  3044. fn(iteration);
  3045. if (breakFunction && breakFunction()) {
  3046. loop.breakLoop();
  3047. break;
  3048. }
  3049. }
  3050. loop.executeNext();
  3051. }, timeout);
  3052. }
  3053. }, callback);
  3054. };
  3055. return AsyncLoop;
  3056. })();
  3057. BABYLON.AsyncLoop = AsyncLoop;
  3058. })(BABYLON || (BABYLON = {}));
  3059. //# sourceMappingURL=babylon.tools.js.map
  3060. var BABYLON;
  3061. (function (BABYLON) {
  3062. var _DepthCullingState = (function () {
  3063. function _DepthCullingState() {
  3064. this._isDepthTestDirty = false;
  3065. this._isDepthMaskDirty = false;
  3066. this._isDepthFuncDirty = false;
  3067. this._isCullFaceDirty = false;
  3068. this._isCullDirty = false;
  3069. }
  3070. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3071. get: function () {
  3072. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3073. },
  3074. enumerable: true,
  3075. configurable: true
  3076. });
  3077. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3078. get: function () {
  3079. return this._cullFace;
  3080. },
  3081. set: function (value) {
  3082. if (this._cullFace === value) {
  3083. return;
  3084. }
  3085. this._cullFace = value;
  3086. this._isCullFaceDirty = true;
  3087. },
  3088. enumerable: true,
  3089. configurable: true
  3090. });
  3091. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3092. get: function () {
  3093. return this._cull;
  3094. },
  3095. set: function (value) {
  3096. if (this._cull === value) {
  3097. return;
  3098. }
  3099. this._cull = value;
  3100. this._isCullDirty = true;
  3101. },
  3102. enumerable: true,
  3103. configurable: true
  3104. });
  3105. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3106. get: function () {
  3107. return this._depthFunc;
  3108. },
  3109. set: function (value) {
  3110. if (this._depthFunc === value) {
  3111. return;
  3112. }
  3113. this._depthFunc = value;
  3114. this._isDepthFuncDirty = true;
  3115. },
  3116. enumerable: true,
  3117. configurable: true
  3118. });
  3119. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3120. get: function () {
  3121. return this._depthMask;
  3122. },
  3123. set: function (value) {
  3124. if (this._depthMask === value) {
  3125. return;
  3126. }
  3127. this._depthMask = value;
  3128. this._isDepthMaskDirty = true;
  3129. },
  3130. enumerable: true,
  3131. configurable: true
  3132. });
  3133. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3134. get: function () {
  3135. return this._depthTest;
  3136. },
  3137. set: function (value) {
  3138. if (this._depthTest === value) {
  3139. return;
  3140. }
  3141. this._depthTest = value;
  3142. this._isDepthTestDirty = true;
  3143. },
  3144. enumerable: true,
  3145. configurable: true
  3146. });
  3147. _DepthCullingState.prototype.reset = function () {
  3148. this._depthMask = true;
  3149. this._depthTest = true;
  3150. this._depthFunc = null;
  3151. this._cull = null;
  3152. this._cullFace = null;
  3153. this._isDepthTestDirty = true;
  3154. this._isDepthMaskDirty = true;
  3155. this._isDepthFuncDirty = false;
  3156. this._isCullFaceDirty = false;
  3157. this._isCullDirty = false;
  3158. };
  3159. _DepthCullingState.prototype.apply = function (gl) {
  3160. if (!this.isDirty) {
  3161. return;
  3162. }
  3163. // Cull
  3164. if (this._isCullDirty) {
  3165. if (this.cull) {
  3166. gl.enable(gl.CULL_FACE);
  3167. } else {
  3168. gl.disable(gl.CULL_FACE);
  3169. }
  3170. this._isCullDirty = false;
  3171. }
  3172. // Cull face
  3173. if (this._isCullFaceDirty) {
  3174. gl.cullFace(this.cullFace);
  3175. this._isCullFaceDirty = false;
  3176. }
  3177. // Depth mask
  3178. if (this._isDepthMaskDirty) {
  3179. gl.depthMask(this.depthMask);
  3180. this._isDepthMaskDirty = false;
  3181. }
  3182. // Depth test
  3183. if (this._isDepthTestDirty) {
  3184. if (this.depthTest) {
  3185. gl.enable(gl.DEPTH_TEST);
  3186. } else {
  3187. gl.disable(gl.DEPTH_TEST);
  3188. }
  3189. this._isDepthTestDirty = false;
  3190. }
  3191. // Depth func
  3192. if (this._isDepthFuncDirty) {
  3193. gl.depthFunc(this.depthFunc);
  3194. this._isDepthFuncDirty = false;
  3195. }
  3196. };
  3197. return _DepthCullingState;
  3198. })();
  3199. BABYLON._DepthCullingState = _DepthCullingState;
  3200. var _AlphaState = (function () {
  3201. function _AlphaState() {
  3202. this._isAlphaBlendDirty = false;
  3203. this._isBlendFunctionParametersDirty = false;
  3204. this._alphaBlend = false;
  3205. this._blendFunctionParameters = new Array(4);
  3206. }
  3207. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3208. get: function () {
  3209. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3210. },
  3211. enumerable: true,
  3212. configurable: true
  3213. });
  3214. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3215. get: function () {
  3216. return this._alphaBlend;
  3217. },
  3218. set: function (value) {
  3219. if (this._alphaBlend === value) {
  3220. return;
  3221. }
  3222. this._alphaBlend = value;
  3223. this._isAlphaBlendDirty = true;
  3224. },
  3225. enumerable: true,
  3226. configurable: true
  3227. });
  3228. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3229. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3230. return;
  3231. }
  3232. this._blendFunctionParameters[0] = value0;
  3233. this._blendFunctionParameters[1] = value1;
  3234. this._blendFunctionParameters[2] = value2;
  3235. this._blendFunctionParameters[3] = value3;
  3236. this._isBlendFunctionParametersDirty = true;
  3237. };
  3238. _AlphaState.prototype.reset = function () {
  3239. this._alphaBlend = false;
  3240. this._blendFunctionParameters[0] = null;
  3241. this._blendFunctionParameters[1] = null;
  3242. this._blendFunctionParameters[2] = null;
  3243. this._blendFunctionParameters[3] = null;
  3244. this._isAlphaBlendDirty = true;
  3245. this._isBlendFunctionParametersDirty = false;
  3246. };
  3247. _AlphaState.prototype.apply = function (gl) {
  3248. if (!this.isDirty) {
  3249. return;
  3250. }
  3251. // Alpha blend
  3252. if (this._isAlphaBlendDirty) {
  3253. if (this._alphaBlend) {
  3254. gl.enable(gl.BLEND);
  3255. } else {
  3256. gl.disable(gl.BLEND);
  3257. }
  3258. this._isAlphaBlendDirty = false;
  3259. }
  3260. // Alpha function
  3261. if (this._isBlendFunctionParametersDirty) {
  3262. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3263. this._isBlendFunctionParametersDirty = false;
  3264. }
  3265. };
  3266. return _AlphaState;
  3267. })();
  3268. BABYLON._AlphaState = _AlphaState;
  3269. var compileShader = function (gl, source, type, defines) {
  3270. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3271. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3272. gl.compileShader(shader);
  3273. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3274. throw new Error(gl.getShaderInfoLog(shader));
  3275. }
  3276. return shader;
  3277. };
  3278. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3279. var magFilter = gl.NEAREST;
  3280. var minFilter = gl.NEAREST;
  3281. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3282. magFilter = gl.LINEAR;
  3283. if (generateMipMaps) {
  3284. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3285. } else {
  3286. minFilter = gl.LINEAR;
  3287. }
  3288. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3289. magFilter = gl.LINEAR;
  3290. if (generateMipMaps) {
  3291. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3292. } else {
  3293. minFilter = gl.LINEAR;
  3294. }
  3295. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3296. magFilter = gl.NEAREST;
  3297. if (generateMipMaps) {
  3298. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3299. } else {
  3300. minFilter = gl.NEAREST;
  3301. }
  3302. }
  3303. return {
  3304. min: minFilter,
  3305. mag: magFilter
  3306. };
  3307. };
  3308. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3309. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3310. var engine = scene.getEngine();
  3311. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3312. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3313. gl.bindTexture(gl.TEXTURE_2D, texture);
  3314. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3315. processFunction(potWidth, potHeight);
  3316. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3317. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3318. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3319. if (!noMipmap && !isCompressed) {
  3320. gl.generateMipmap(gl.TEXTURE_2D);
  3321. }
  3322. gl.bindTexture(gl.TEXTURE_2D, null);
  3323. engine._activeTexturesCache = [];
  3324. texture._baseWidth = width;
  3325. texture._baseHeight = height;
  3326. texture._width = potWidth;
  3327. texture._height = potHeight;
  3328. texture.isReady = true;
  3329. texture.samplingMode = samplingMode;
  3330. scene._removePendingData(texture);
  3331. };
  3332. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3333. var onload = function () {
  3334. loadedImages[index] = img;
  3335. loadedImages._internalCount++;
  3336. scene._removePendingData(img);
  3337. if (loadedImages._internalCount === 6) {
  3338. onfinish(loadedImages);
  3339. }
  3340. };
  3341. var onerror = function () {
  3342. scene._removePendingData(img);
  3343. };
  3344. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3345. scene._addPendingData(img);
  3346. };
  3347. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3348. var loadedImages = [];
  3349. loadedImages._internalCount = 0;
  3350. for (var index = 0; index < 6; index++) {
  3351. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3352. }
  3353. };
  3354. var EngineCapabilities = (function () {
  3355. function EngineCapabilities() {
  3356. }
  3357. return EngineCapabilities;
  3358. })();
  3359. BABYLON.EngineCapabilities = EngineCapabilities;
  3360. var Engine = (function () {
  3361. function Engine(canvas, antialias, options) {
  3362. var _this = this;
  3363. // Public members
  3364. this.isFullscreen = false;
  3365. this.isPointerLock = false;
  3366. this.cullBackFaces = true;
  3367. this.renderEvenInBackground = true;
  3368. this.scenes = new Array();
  3369. this._windowIsBackground = false;
  3370. this._loadingDivBackgroundColor = "black";
  3371. this._drawCalls = 0;
  3372. this._renderingQueueLaunched = false;
  3373. this._activeRenderLoops = [];
  3374. // FPS
  3375. this.fpsRange = 60;
  3376. this.previousFramesDuration = [];
  3377. this.fps = 60;
  3378. this.deltaTime = 0;
  3379. // States
  3380. this._depthCullingState = new _DepthCullingState();
  3381. this._alphaState = new _AlphaState();
  3382. this._alphaMode = Engine.ALPHA_DISABLE;
  3383. // Cache
  3384. this._loadedTexturesCache = new Array();
  3385. this._activeTexturesCache = new Array();
  3386. this._compiledEffects = {};
  3387. this._uintIndicesCurrentlySet = false;
  3388. this._renderingCanvas = canvas;
  3389. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3390. options = options || {};
  3391. options.antialias = antialias;
  3392. try {
  3393. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3394. } catch (e) {
  3395. throw new Error("WebGL not supported");
  3396. }
  3397. if (!this._gl) {
  3398. throw new Error("WebGL not supported");
  3399. }
  3400. this._onBlur = function () {
  3401. _this._windowIsBackground = true;
  3402. };
  3403. this._onFocus = function () {
  3404. _this._windowIsBackground = false;
  3405. };
  3406. window.addEventListener("blur", this._onBlur);
  3407. window.addEventListener("focus", this._onFocus);
  3408. // Textures
  3409. this._workingCanvas = document.createElement("canvas");
  3410. this._workingContext = this._workingCanvas.getContext("2d");
  3411. // Viewport
  3412. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3413. this.resize();
  3414. // Caps
  3415. this._caps = new EngineCapabilities();
  3416. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3417. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3418. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3419. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3420. // Infos
  3421. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3422. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3423. if (rendererInfo != null) {
  3424. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3425. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3426. }
  3427. if (!this._glVendor) {
  3428. this._glVendor = "Unknown vendor";
  3429. }
  3430. if (!this._glRenderer) {
  3431. this._glRenderer = "Unknown renderer";
  3432. }
  3433. // Extensions
  3434. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3435. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3436. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3437. 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');
  3438. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3439. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3440. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3441. // Depth buffer
  3442. this.setDepthBuffer(true);
  3443. this.setDepthFunctionToLessOrEqual();
  3444. this.setDepthWrite(true);
  3445. // Fullscreen
  3446. this._onFullscreenChange = function () {
  3447. if (document.fullscreen !== undefined) {
  3448. _this.isFullscreen = document.fullscreen;
  3449. } else if (document.mozFullScreen !== undefined) {
  3450. _this.isFullscreen = document.mozFullScreen;
  3451. } else if (document.webkitIsFullScreen !== undefined) {
  3452. _this.isFullscreen = document.webkitIsFullScreen;
  3453. } else if (document.msIsFullScreen !== undefined) {
  3454. _this.isFullscreen = document.msIsFullScreen;
  3455. }
  3456. // Pointer lock
  3457. if (_this.isFullscreen && _this._pointerLockRequested) {
  3458. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3459. if (canvas.requestPointerLock) {
  3460. canvas.requestPointerLock();
  3461. }
  3462. }
  3463. };
  3464. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3465. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3466. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3467. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3468. // Pointer lock
  3469. this._onPointerLockChange = function () {
  3470. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3471. };
  3472. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3473. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3474. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3475. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3476. this._audioEngine = new BABYLON.AudioEngine();
  3477. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3478. }
  3479. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3480. get: function () {
  3481. return Engine._ALPHA_DISABLE;
  3482. },
  3483. enumerable: true,
  3484. configurable: true
  3485. });
  3486. Object.defineProperty(Engine, "ALPHA_ADD", {
  3487. get: function () {
  3488. return Engine._ALPHA_ADD;
  3489. },
  3490. enumerable: true,
  3491. configurable: true
  3492. });
  3493. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3494. get: function () {
  3495. return Engine._ALPHA_COMBINE;
  3496. },
  3497. enumerable: true,
  3498. configurable: true
  3499. });
  3500. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3501. get: function () {
  3502. return Engine._DELAYLOADSTATE_NONE;
  3503. },
  3504. enumerable: true,
  3505. configurable: true
  3506. });
  3507. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3508. get: function () {
  3509. return Engine._DELAYLOADSTATE_LOADED;
  3510. },
  3511. enumerable: true,
  3512. configurable: true
  3513. });
  3514. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3515. get: function () {
  3516. return Engine._DELAYLOADSTATE_LOADING;
  3517. },
  3518. enumerable: true,
  3519. configurable: true
  3520. });
  3521. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3522. get: function () {
  3523. return Engine._DELAYLOADSTATE_NOTLOADED;
  3524. },
  3525. enumerable: true,
  3526. configurable: true
  3527. });
  3528. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3529. get: function () {
  3530. return Engine._TEXTUREFORMAT_ALPHA;
  3531. },
  3532. enumerable: true,
  3533. configurable: true
  3534. });
  3535. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3536. get: function () {
  3537. return Engine._TEXTUREFORMAT_LUMINANCE;
  3538. },
  3539. enumerable: true,
  3540. configurable: true
  3541. });
  3542. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3543. get: function () {
  3544. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3545. },
  3546. enumerable: true,
  3547. configurable: true
  3548. });
  3549. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3550. get: function () {
  3551. return Engine._TEXTUREFORMAT_RGB;
  3552. },
  3553. enumerable: true,
  3554. configurable: true
  3555. });
  3556. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3557. get: function () {
  3558. return Engine._TEXTUREFORMAT_RGBA;
  3559. },
  3560. enumerable: true,
  3561. configurable: true
  3562. });
  3563. Object.defineProperty(Engine, "Version", {
  3564. get: function () {
  3565. return "2.0.0";
  3566. },
  3567. enumerable: true,
  3568. configurable: true
  3569. });
  3570. Engine.prototype.getGlInfo = function () {
  3571. return {
  3572. vendor: this._glVendor,
  3573. renderer: this._glRenderer,
  3574. version: this._glVersion
  3575. };
  3576. };
  3577. Engine.prototype.getAudioEngine = function () {
  3578. return this._audioEngine;
  3579. };
  3580. Engine.prototype.getAspectRatio = function (camera) {
  3581. var viewport = camera.viewport;
  3582. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3583. };
  3584. Engine.prototype.getRenderWidth = function () {
  3585. if (this._currentRenderTarget) {
  3586. return this._currentRenderTarget._width;
  3587. }
  3588. return this._renderingCanvas.width;
  3589. };
  3590. Engine.prototype.getRenderHeight = function () {
  3591. if (this._currentRenderTarget) {
  3592. return this._currentRenderTarget._height;
  3593. }
  3594. return this._renderingCanvas.height;
  3595. };
  3596. Engine.prototype.getRenderingCanvas = function () {
  3597. return this._renderingCanvas;
  3598. };
  3599. Engine.prototype.getRenderingCanvasClientRect = function () {
  3600. return this._renderingCanvas.getBoundingClientRect();
  3601. };
  3602. Engine.prototype.setHardwareScalingLevel = function (level) {
  3603. this._hardwareScalingLevel = level;
  3604. this.resize();
  3605. };
  3606. Engine.prototype.getHardwareScalingLevel = function () {
  3607. return this._hardwareScalingLevel;
  3608. };
  3609. Engine.prototype.getLoadedTexturesCache = function () {
  3610. return this._loadedTexturesCache;
  3611. };
  3612. Engine.prototype.getCaps = function () {
  3613. return this._caps;
  3614. };
  3615. Object.defineProperty(Engine.prototype, "drawCalls", {
  3616. get: function () {
  3617. return this._drawCalls;
  3618. },
  3619. enumerable: true,
  3620. configurable: true
  3621. });
  3622. // Methods
  3623. Engine.prototype.resetDrawCalls = function () {
  3624. this._drawCalls = 0;
  3625. };
  3626. Engine.prototype.setDepthFunctionToGreater = function () {
  3627. this._depthCullingState.depthFunc = this._gl.GREATER;
  3628. };
  3629. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3630. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3631. };
  3632. Engine.prototype.setDepthFunctionToLess = function () {
  3633. this._depthCullingState.depthFunc = this._gl.LESS;
  3634. };
  3635. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3636. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3637. };
  3638. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3639. if (!renderFunction) {
  3640. this._activeRenderLoops = [];
  3641. return;
  3642. }
  3643. var index = this._activeRenderLoops.indexOf(renderFunction);
  3644. if (index >= 0) {
  3645. this._activeRenderLoops.splice(index, 1);
  3646. }
  3647. };
  3648. Engine.prototype._renderLoop = function () {
  3649. var _this = this;
  3650. var shouldRender = true;
  3651. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3652. shouldRender = false;
  3653. }
  3654. if (shouldRender) {
  3655. // Start new frame
  3656. this.beginFrame();
  3657. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3658. var renderFunction = this._activeRenderLoops[index];
  3659. renderFunction();
  3660. }
  3661. // Present
  3662. this.endFrame();
  3663. }
  3664. if (this._activeRenderLoops.length > 0) {
  3665. // Register new frame
  3666. BABYLON.Tools.QueueNewFrame(function () {
  3667. _this._renderLoop();
  3668. });
  3669. } else {
  3670. this._renderingQueueLaunched = false;
  3671. }
  3672. };
  3673. Engine.prototype.runRenderLoop = function (renderFunction) {
  3674. var _this = this;
  3675. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3676. return;
  3677. }
  3678. this._activeRenderLoops.push(renderFunction);
  3679. if (!this._renderingQueueLaunched) {
  3680. this._renderingQueueLaunched = true;
  3681. BABYLON.Tools.QueueNewFrame(function () {
  3682. _this._renderLoop();
  3683. });
  3684. }
  3685. };
  3686. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3687. if (this.isFullscreen) {
  3688. BABYLON.Tools.ExitFullscreen();
  3689. } else {
  3690. this._pointerLockRequested = requestPointerLock;
  3691. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3692. }
  3693. };
  3694. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3695. this.applyStates();
  3696. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3697. if (this._depthCullingState.depthMask) {
  3698. this._gl.clearDepth(1.0);
  3699. }
  3700. var mode = 0;
  3701. if (backBuffer)
  3702. mode |= this._gl.COLOR_BUFFER_BIT;
  3703. if (depthStencil && this._depthCullingState.depthMask)
  3704. mode |= this._gl.DEPTH_BUFFER_BIT;
  3705. this._gl.clear(mode);
  3706. };
  3707. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3708. var width = requiredWidth || this._renderingCanvas.width;
  3709. var height = requiredHeight || this._renderingCanvas.height;
  3710. var x = viewport.x || 0;
  3711. var y = viewport.y || 0;
  3712. this._cachedViewport = viewport;
  3713. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3714. };
  3715. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3716. this._cachedViewport = null;
  3717. this._gl.viewport(x, y, width, height);
  3718. };
  3719. Engine.prototype.beginFrame = function () {
  3720. this._measureFps();
  3721. };
  3722. Engine.prototype.endFrame = function () {
  3723. this.flushFramebuffer();
  3724. };
  3725. Engine.prototype.resize = function () {
  3726. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3727. };
  3728. Engine.prototype.setSize = function (width, height) {
  3729. this._renderingCanvas.width = width;
  3730. this._renderingCanvas.height = height;
  3731. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3732. };
  3733. Engine.prototype.bindFramebuffer = function (texture) {
  3734. this._currentRenderTarget = texture;
  3735. var gl = this._gl;
  3736. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3737. this._gl.viewport(0, 0, texture._width, texture._height);
  3738. this.wipeCaches();
  3739. };
  3740. Engine.prototype.unBindFramebuffer = function (texture) {
  3741. this._currentRenderTarget = null;
  3742. if (texture.generateMipMaps) {
  3743. var gl = this._gl;
  3744. gl.bindTexture(gl.TEXTURE_2D, texture);
  3745. gl.generateMipmap(gl.TEXTURE_2D);
  3746. gl.bindTexture(gl.TEXTURE_2D, null);
  3747. }
  3748. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3749. };
  3750. Engine.prototype.flushFramebuffer = function () {
  3751. // this._gl.flush();
  3752. };
  3753. Engine.prototype.restoreDefaultFramebuffer = function () {
  3754. this._currentRenderTarget = null;
  3755. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3756. this.setViewport(this._cachedViewport);
  3757. this.wipeCaches();
  3758. };
  3759. // VBOs
  3760. Engine.prototype._resetVertexBufferBinding = function () {
  3761. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3762. this._cachedVertexBuffers = null;
  3763. };
  3764. Engine.prototype.createVertexBuffer = function (vertices) {
  3765. var vbo = this._gl.createBuffer();
  3766. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3767. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3768. this._resetVertexBufferBinding();
  3769. vbo.references = 1;
  3770. return vbo;
  3771. };
  3772. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3773. var vbo = this._gl.createBuffer();
  3774. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3775. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3776. this._resetVertexBufferBinding();
  3777. vbo.references = 1;
  3778. return vbo;
  3779. };
  3780. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3781. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3782. if (offset === undefined) {
  3783. offset = 0;
  3784. }
  3785. if (vertices instanceof Float32Array) {
  3786. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3787. } else {
  3788. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3789. }
  3790. this._resetVertexBufferBinding();
  3791. };
  3792. Engine.prototype._resetIndexBufferBinding = function () {
  3793. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3794. this._cachedIndexBuffer = null;
  3795. };
  3796. Engine.prototype.createIndexBuffer = function (indices) {
  3797. var vbo = this._gl.createBuffer();
  3798. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3799. // Check for 32 bits indices
  3800. var arrayBuffer;
  3801. var need32Bits = false;
  3802. if (this._caps.uintIndices) {
  3803. for (var index = 0; index < indices.length; index++) {
  3804. if (indices[index] > 65535) {
  3805. need32Bits = true;
  3806. break;
  3807. }
  3808. }
  3809. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3810. } else {
  3811. arrayBuffer = new Uint16Array(indices);
  3812. }
  3813. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3814. this._resetIndexBufferBinding();
  3815. vbo.references = 1;
  3816. vbo.is32Bits = need32Bits;
  3817. return vbo;
  3818. };
  3819. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3820. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3821. this._cachedVertexBuffers = vertexBuffer;
  3822. this._cachedEffectForVertexBuffers = effect;
  3823. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3824. var offset = 0;
  3825. for (var index = 0; index < vertexDeclaration.length; index++) {
  3826. var order = effect.getAttributeLocation(index);
  3827. if (order >= 0) {
  3828. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3829. }
  3830. offset += vertexDeclaration[index] * 4;
  3831. }
  3832. }
  3833. if (this._cachedIndexBuffer !== indexBuffer) {
  3834. this._cachedIndexBuffer = indexBuffer;
  3835. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3836. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3837. }
  3838. };
  3839. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3840. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3841. this._cachedVertexBuffers = vertexBuffers;
  3842. this._cachedEffectForVertexBuffers = effect;
  3843. var attributes = effect.getAttributesNames();
  3844. for (var index = 0; index < attributes.length; index++) {
  3845. var order = effect.getAttributeLocation(index);
  3846. if (order >= 0) {
  3847. var vertexBuffer = vertexBuffers[attributes[index]];
  3848. if (!vertexBuffer) {
  3849. continue;
  3850. }
  3851. var stride = vertexBuffer.getStrideSize();
  3852. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3853. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3854. }
  3855. }
  3856. }
  3857. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3858. this._cachedIndexBuffer = indexBuffer;
  3859. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3860. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3861. }
  3862. };
  3863. Engine.prototype._releaseBuffer = function (buffer) {
  3864. buffer.references--;
  3865. if (buffer.references === 0) {
  3866. this._gl.deleteBuffer(buffer);
  3867. return true;
  3868. }
  3869. return false;
  3870. };
  3871. Engine.prototype.createInstancesBuffer = function (capacity) {
  3872. var buffer = this._gl.createBuffer();
  3873. buffer.capacity = capacity;
  3874. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3875. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3876. return buffer;
  3877. };
  3878. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3879. this._gl.deleteBuffer(buffer);
  3880. };
  3881. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3882. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3883. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3884. for (var index = 0; index < 4; index++) {
  3885. var offsetLocation = offsetLocations[index];
  3886. this._gl.enableVertexAttribArray(offsetLocation);
  3887. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3888. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3889. }
  3890. };
  3891. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3892. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3893. for (var index = 0; index < 4; index++) {
  3894. var offsetLocation = offsetLocations[index];
  3895. this._gl.disableVertexAttribArray(offsetLocation);
  3896. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3897. }
  3898. };
  3899. Engine.prototype.applyStates = function () {
  3900. this._depthCullingState.apply(this._gl);
  3901. this._alphaState.apply(this._gl);
  3902. };
  3903. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3904. // Apply states
  3905. this.applyStates();
  3906. this._drawCalls++;
  3907. // Render
  3908. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3909. if (instancesCount) {
  3910. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3911. return;
  3912. }
  3913. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3914. };
  3915. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3916. // Apply states
  3917. this.applyStates();
  3918. this._drawCalls++;
  3919. if (instancesCount) {
  3920. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3921. return;
  3922. }
  3923. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3924. };
  3925. // Shaders
  3926. Engine.prototype._releaseEffect = function (effect) {
  3927. if (this._compiledEffects[effect._key]) {
  3928. delete this._compiledEffects[effect._key];
  3929. if (effect.getProgram()) {
  3930. this._gl.deleteProgram(effect.getProgram());
  3931. }
  3932. }
  3933. };
  3934. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3935. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3936. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3937. var name = vertex + "+" + fragment + "@" + defines;
  3938. if (this._compiledEffects[name]) {
  3939. return this._compiledEffects[name];
  3940. }
  3941. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3942. effect._key = name;
  3943. this._compiledEffects[name] = effect;
  3944. return effect;
  3945. };
  3946. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3947. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3948. if (typeof samplers === "undefined") { samplers = []; }
  3949. if (typeof defines === "undefined") { defines = ""; }
  3950. return this.createEffect({
  3951. vertex: "particles",
  3952. fragmentElement: fragmentName
  3953. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3954. };
  3955. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3956. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3957. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3958. var shaderProgram = this._gl.createProgram();
  3959. this._gl.attachShader(shaderProgram, vertexShader);
  3960. this._gl.attachShader(shaderProgram, fragmentShader);
  3961. this._gl.linkProgram(shaderProgram);
  3962. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3963. if (!linked) {
  3964. var error = this._gl.getProgramInfoLog(shaderProgram);
  3965. if (error) {
  3966. throw new Error(error);
  3967. }
  3968. }
  3969. this._gl.deleteShader(vertexShader);
  3970. this._gl.deleteShader(fragmentShader);
  3971. return shaderProgram;
  3972. };
  3973. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3974. var results = [];
  3975. for (var index = 0; index < uniformsNames.length; index++) {
  3976. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3977. }
  3978. return results;
  3979. };
  3980. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3981. var results = [];
  3982. for (var index = 0; index < attributesNames.length; index++) {
  3983. try {
  3984. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3985. } catch (e) {
  3986. results.push(-1);
  3987. }
  3988. }
  3989. return results;
  3990. };
  3991. Engine.prototype.enableEffect = function (effect) {
  3992. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3993. if (effect && effect.onBind) {
  3994. effect.onBind(effect);
  3995. }
  3996. return;
  3997. }
  3998. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3999. // Use program
  4000. this._gl.useProgram(effect.getProgram());
  4001. for (var i in this._vertexAttribArrays) {
  4002. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4003. continue;
  4004. }
  4005. this._vertexAttribArrays[i] = false;
  4006. this._gl.disableVertexAttribArray(i);
  4007. }
  4008. var attributesCount = effect.getAttributesCount();
  4009. for (var index = 0; index < attributesCount; index++) {
  4010. // Attributes
  4011. var order = effect.getAttributeLocation(index);
  4012. if (order >= 0) {
  4013. this._vertexAttribArrays[order] = true;
  4014. this._gl.enableVertexAttribArray(order);
  4015. }
  4016. }
  4017. this._currentEffect = effect;
  4018. if (effect.onBind) {
  4019. effect.onBind(effect);
  4020. }
  4021. };
  4022. Engine.prototype.setArray = function (uniform, array) {
  4023. if (!uniform)
  4024. return;
  4025. this._gl.uniform1fv(uniform, array);
  4026. };
  4027. Engine.prototype.setMatrices = function (uniform, matrices) {
  4028. if (!uniform)
  4029. return;
  4030. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4031. };
  4032. Engine.prototype.setMatrix = function (uniform, matrix) {
  4033. if (!uniform)
  4034. return;
  4035. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4036. };
  4037. Engine.prototype.setFloat = function (uniform, value) {
  4038. if (!uniform)
  4039. return;
  4040. this._gl.uniform1f(uniform, value);
  4041. };
  4042. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4043. if (!uniform)
  4044. return;
  4045. this._gl.uniform2f(uniform, x, y);
  4046. };
  4047. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4048. if (!uniform)
  4049. return;
  4050. this._gl.uniform3f(uniform, x, y, z);
  4051. };
  4052. Engine.prototype.setBool = function (uniform, bool) {
  4053. if (!uniform)
  4054. return;
  4055. this._gl.uniform1i(uniform, bool);
  4056. };
  4057. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4058. if (!uniform)
  4059. return;
  4060. this._gl.uniform4f(uniform, x, y, z, w);
  4061. };
  4062. Engine.prototype.setColor3 = function (uniform, color3) {
  4063. if (!uniform)
  4064. return;
  4065. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4066. };
  4067. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4068. if (!uniform)
  4069. return;
  4070. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4071. };
  4072. // States
  4073. Engine.prototype.setState = function (culling, force) {
  4074. // Culling
  4075. if (this._depthCullingState.cull !== culling || force) {
  4076. if (culling) {
  4077. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4078. this._depthCullingState.cull = true;
  4079. } else {
  4080. this._depthCullingState.cull = false;
  4081. }
  4082. }
  4083. };
  4084. Engine.prototype.setDepthBuffer = function (enable) {
  4085. this._depthCullingState.depthTest = enable;
  4086. };
  4087. Engine.prototype.getDepthWrite = function () {
  4088. return this._depthCullingState.depthMask;
  4089. };
  4090. Engine.prototype.setDepthWrite = function (enable) {
  4091. this._depthCullingState.depthMask = enable;
  4092. };
  4093. Engine.prototype.setColorWrite = function (enable) {
  4094. this._gl.colorMask(enable, enable, enable, enable);
  4095. };
  4096. Engine.prototype.setAlphaMode = function (mode) {
  4097. switch (mode) {
  4098. case Engine.ALPHA_DISABLE:
  4099. this.setDepthWrite(true);
  4100. this._alphaState.alphaBlend = false;
  4101. break;
  4102. case Engine.ALPHA_COMBINE:
  4103. this.setDepthWrite(false);
  4104. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4105. this._alphaState.alphaBlend = true;
  4106. break;
  4107. case Engine.ALPHA_ADD:
  4108. this.setDepthWrite(false);
  4109. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4110. this._alphaState.alphaBlend = true;
  4111. break;
  4112. }
  4113. this._alphaMode = mode;
  4114. };
  4115. Engine.prototype.getAlphaMode = function () {
  4116. return this._alphaMode;
  4117. };
  4118. Engine.prototype.setAlphaTesting = function (enable) {
  4119. this._alphaTest = enable;
  4120. };
  4121. Engine.prototype.getAlphaTesting = function () {
  4122. return this._alphaTest;
  4123. };
  4124. // Textures
  4125. Engine.prototype.wipeCaches = function () {
  4126. this._activeTexturesCache = [];
  4127. this._currentEffect = null;
  4128. this._depthCullingState.reset();
  4129. this._alphaState.reset();
  4130. this._cachedVertexBuffers = null;
  4131. this._cachedIndexBuffer = null;
  4132. this._cachedEffectForVertexBuffers = null;
  4133. };
  4134. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4135. var gl = this._gl;
  4136. gl.bindTexture(gl.TEXTURE_2D, texture);
  4137. var magFilter = gl.NEAREST;
  4138. var minFilter = gl.NEAREST;
  4139. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4140. magFilter = gl.LINEAR;
  4141. minFilter = gl.LINEAR;
  4142. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4143. magFilter = gl.LINEAR;
  4144. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4145. }
  4146. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4147. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4148. gl.bindTexture(gl.TEXTURE_2D, null);
  4149. texture.samplingMode = samplingMode;
  4150. };
  4151. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4152. var _this = this;
  4153. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4154. if (typeof onLoad === "undefined") { onLoad = null; }
  4155. if (typeof onError === "undefined") { onError = null; }
  4156. if (typeof buffer === "undefined") { buffer = null; }
  4157. var texture = this._gl.createTexture();
  4158. var extension;
  4159. var fromData = false;
  4160. if (url.substr(0, 5) === "data:") {
  4161. fromData = true;
  4162. }
  4163. if (!fromData)
  4164. extension = url.substr(url.length - 4, 4).toLowerCase();
  4165. else {
  4166. var oldUrl = url;
  4167. fromData = oldUrl.split(':');
  4168. url = oldUrl;
  4169. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4170. }
  4171. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4172. var isTGA = (extension === ".tga");
  4173. scene._addPendingData(texture);
  4174. texture.url = url;
  4175. texture.noMipmap = noMipmap;
  4176. texture.references = 1;
  4177. this._loadedTexturesCache.push(texture);
  4178. var onerror = function () {
  4179. scene._removePendingData(texture);
  4180. if (onError) {
  4181. onError();
  4182. }
  4183. };
  4184. if (isTGA) {
  4185. var callback = function (arrayBuffer) {
  4186. var data = new Uint8Array(arrayBuffer);
  4187. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4188. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4189. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4190. if (onLoad) {
  4191. onLoad();
  4192. }
  4193. }, samplingMode);
  4194. };
  4195. if (!(fromData instanceof Array))
  4196. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4197. callback(arrayBuffer);
  4198. }, onerror, scene.database, true);
  4199. else
  4200. callback(buffer);
  4201. } else if (isDDS) {
  4202. callback = function (data) {
  4203. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4204. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4205. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4206. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4207. if (onLoad) {
  4208. onLoad();
  4209. }
  4210. }, samplingMode);
  4211. };
  4212. if (!(fromData instanceof Array))
  4213. BABYLON.Tools.LoadFile(url, function (data) {
  4214. callback(data);
  4215. }, onerror, scene.database, true);
  4216. else
  4217. callback(buffer);
  4218. } else {
  4219. var onload = function (img) {
  4220. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4221. var isPot = (img.width === potWidth && img.height === potHeight);
  4222. if (!isPot) {
  4223. _this._workingCanvas.width = potWidth;
  4224. _this._workingCanvas.height = potHeight;
  4225. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4226. _this._workingContext.imageSmoothingEnabled = false;
  4227. _this._workingContext.mozImageSmoothingEnabled = false;
  4228. _this._workingContext.oImageSmoothingEnabled = false;
  4229. _this._workingContext.webkitImageSmoothingEnabled = false;
  4230. _this._workingContext.msImageSmoothingEnabled = false;
  4231. }
  4232. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4233. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4234. _this._workingContext.imageSmoothingEnabled = true;
  4235. _this._workingContext.mozImageSmoothingEnabled = true;
  4236. _this._workingContext.oImageSmoothingEnabled = true;
  4237. _this._workingContext.webkitImageSmoothingEnabled = true;
  4238. _this._workingContext.msImageSmoothingEnabled = true;
  4239. }
  4240. }
  4241. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4242. if (onLoad) {
  4243. onLoad();
  4244. }
  4245. }, samplingMode);
  4246. };
  4247. if (!(fromData instanceof Array))
  4248. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4249. else
  4250. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4251. }
  4252. return texture;
  4253. };
  4254. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4255. var texture = this._gl.createTexture();
  4256. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4257. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4258. // Format
  4259. var internalFormat = this._gl.RGBA;
  4260. switch (format) {
  4261. case Engine.TEXTUREFORMAT_ALPHA:
  4262. internalFormat = this._gl.ALPHA;
  4263. break;
  4264. case Engine.TEXTUREFORMAT_LUMINANCE:
  4265. internalFormat = this._gl.LUMINANCE;
  4266. break;
  4267. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4268. internalFormat = this._gl.LUMINANCE_ALPHA;
  4269. break;
  4270. case Engine.TEXTUREFORMAT_RGB:
  4271. internalFormat = this._gl.RGB;
  4272. break;
  4273. case Engine.TEXTUREFORMAT_RGBA:
  4274. internalFormat = this._gl.RGBA;
  4275. break;
  4276. }
  4277. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4278. if (generateMipMaps) {
  4279. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4280. }
  4281. // Filters
  4282. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4283. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4284. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4285. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4286. this._activeTexturesCache = [];
  4287. texture._baseWidth = width;
  4288. texture._baseHeight = height;
  4289. texture._width = width;
  4290. texture._height = height;
  4291. texture.isReady = true;
  4292. texture.references = 1;
  4293. texture.samplingMode = samplingMode;
  4294. this._loadedTexturesCache.push(texture);
  4295. return texture;
  4296. };
  4297. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4298. var texture = this._gl.createTexture();
  4299. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4300. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4301. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4302. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4303. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4304. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4305. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4306. this._activeTexturesCache = [];
  4307. texture._baseWidth = width;
  4308. texture._baseHeight = height;
  4309. texture._width = width;
  4310. texture._height = height;
  4311. texture.isReady = false;
  4312. texture.generateMipMaps = generateMipMaps;
  4313. texture.references = 1;
  4314. texture.samplingMode = samplingMode;
  4315. this._loadedTexturesCache.push(texture);
  4316. return texture;
  4317. };
  4318. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4319. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4320. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4321. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4322. if (texture.generateMipMaps) {
  4323. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4324. }
  4325. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4326. this._activeTexturesCache = [];
  4327. texture.isReady = true;
  4328. };
  4329. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4330. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4331. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4332. // Scale the video if it is a NPOT using the current working canvas
  4333. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4334. if (!texture._workingCanvas) {
  4335. texture._workingCanvas = document.createElement("canvas");
  4336. texture._workingContext = texture._workingCanvas.getContext("2d");
  4337. texture._workingCanvas.width = texture._width;
  4338. texture._workingCanvas.height = texture._height;
  4339. }
  4340. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4341. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4342. } else {
  4343. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4344. }
  4345. if (texture.generateMipMaps) {
  4346. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4347. }
  4348. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4349. this._activeTexturesCache = [];
  4350. texture.isReady = true;
  4351. };
  4352. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4353. // old version had a "generateMipMaps" arg instead of options.
  4354. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4355. // in the same way, generateDepthBuffer is defaulted to true
  4356. var generateMipMaps = false;
  4357. var generateDepthBuffer = true;
  4358. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4359. if (options !== undefined) {
  4360. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4361. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4362. if (options.samplingMode !== undefined) {
  4363. samplingMode = options.samplingMode;
  4364. }
  4365. }
  4366. var gl = this._gl;
  4367. var texture = gl.createTexture();
  4368. gl.bindTexture(gl.TEXTURE_2D, texture);
  4369. var width = size.width || size;
  4370. var height = size.height || size;
  4371. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4372. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4373. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4374. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4375. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4376. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  4377. var depthBuffer;
  4378. // Create the depth buffer
  4379. if (generateDepthBuffer) {
  4380. depthBuffer = gl.createRenderbuffer();
  4381. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4382. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4383. }
  4384. // Create the framebuffer
  4385. var framebuffer = gl.createFramebuffer();
  4386. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4387. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4388. if (generateDepthBuffer) {
  4389. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4390. }
  4391. // Unbind
  4392. gl.bindTexture(gl.TEXTURE_2D, null);
  4393. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4394. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4395. texture._framebuffer = framebuffer;
  4396. if (generateDepthBuffer) {
  4397. texture._depthBuffer = depthBuffer;
  4398. }
  4399. texture._width = width;
  4400. texture._height = height;
  4401. texture.isReady = true;
  4402. texture.generateMipMaps = generateMipMaps;
  4403. texture.references = 1;
  4404. texture.samplingMode = samplingMode;
  4405. this._activeTexturesCache = [];
  4406. this._loadedTexturesCache.push(texture);
  4407. return texture;
  4408. };
  4409. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4410. var _this = this;
  4411. var gl = this._gl;
  4412. var texture = gl.createTexture();
  4413. texture.isCube = true;
  4414. texture.url = rootUrl;
  4415. texture.references = 1;
  4416. this._loadedTexturesCache.push(texture);
  4417. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4418. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4419. if (isDDS) {
  4420. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4421. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4422. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4423. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4424. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4425. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4426. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4427. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4428. }
  4429. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4430. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4431. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4432. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4433. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4434. _this._activeTexturesCache = [];
  4435. texture._width = info.width;
  4436. texture._height = info.height;
  4437. texture.isReady = true;
  4438. }, null, null, true);
  4439. } else {
  4440. cascadeLoad(rootUrl, scene, function (imgs) {
  4441. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4442. var height = width;
  4443. _this._workingCanvas.width = width;
  4444. _this._workingCanvas.height = height;
  4445. var faces = [
  4446. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4447. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4448. ];
  4449. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4450. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4451. for (var index = 0; index < faces.length; index++) {
  4452. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4453. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4454. }
  4455. if (!noMipmap) {
  4456. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4457. }
  4458. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4459. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4460. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4462. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4463. _this._activeTexturesCache = [];
  4464. texture._width = width;
  4465. texture._height = height;
  4466. texture.isReady = true;
  4467. }, extensions);
  4468. }
  4469. return texture;
  4470. };
  4471. Engine.prototype._releaseTexture = function (texture) {
  4472. var gl = this._gl;
  4473. if (texture._framebuffer) {
  4474. gl.deleteFramebuffer(texture._framebuffer);
  4475. }
  4476. if (texture._depthBuffer) {
  4477. gl.deleteRenderbuffer(texture._depthBuffer);
  4478. }
  4479. gl.deleteTexture(texture);
  4480. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4481. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4482. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4483. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4484. this._activeTexturesCache[channel] = null;
  4485. }
  4486. var index = this._loadedTexturesCache.indexOf(texture);
  4487. if (index !== -1) {
  4488. this._loadedTexturesCache.splice(index, 1);
  4489. }
  4490. };
  4491. Engine.prototype.bindSamplers = function (effect) {
  4492. this._gl.useProgram(effect.getProgram());
  4493. var samplers = effect.getSamplers();
  4494. for (var index = 0; index < samplers.length; index++) {
  4495. var uniform = effect.getUniform(samplers[index]);
  4496. this._gl.uniform1i(uniform, index);
  4497. }
  4498. this._currentEffect = null;
  4499. };
  4500. Engine.prototype._bindTexture = function (channel, texture) {
  4501. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4502. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4503. this._activeTexturesCache[channel] = null;
  4504. };
  4505. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4506. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4507. };
  4508. Engine.prototype.setTexture = function (channel, texture) {
  4509. if (channel < 0) {
  4510. return;
  4511. }
  4512. // Not ready?
  4513. if (!texture || !texture.isReady()) {
  4514. if (this._activeTexturesCache[channel] != null) {
  4515. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4516. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4517. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4518. this._activeTexturesCache[channel] = null;
  4519. }
  4520. return;
  4521. }
  4522. // Video
  4523. if (texture instanceof BABYLON.VideoTexture) {
  4524. if (texture.update()) {
  4525. this._activeTexturesCache[channel] = null;
  4526. }
  4527. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4528. texture.delayLoad();
  4529. return;
  4530. }
  4531. if (this._activeTexturesCache[channel] === texture) {
  4532. return;
  4533. }
  4534. this._activeTexturesCache[channel] = texture;
  4535. var internalTexture = texture.getInternalTexture();
  4536. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4537. if (internalTexture.isCube) {
  4538. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4539. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4540. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4541. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4542. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4543. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4544. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4545. }
  4546. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4547. } else {
  4548. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4549. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4550. internalTexture._cachedWrapU = texture.wrapU;
  4551. switch (texture.wrapU) {
  4552. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4553. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4554. break;
  4555. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4556. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4557. break;
  4558. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4559. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4560. break;
  4561. }
  4562. }
  4563. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4564. internalTexture._cachedWrapV = texture.wrapV;
  4565. switch (texture.wrapV) {
  4566. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4567. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4568. break;
  4569. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4570. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4571. break;
  4572. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4573. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4574. break;
  4575. }
  4576. }
  4577. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4578. }
  4579. };
  4580. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4581. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4582. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4583. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4584. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4585. }
  4586. };
  4587. Engine.prototype.readPixels = function (x, y, width, height) {
  4588. var data = new Uint8Array(height * width * 4);
  4589. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4590. return data;
  4591. };
  4592. // Dispose
  4593. Engine.prototype.dispose = function () {
  4594. this.hideLoadingUI();
  4595. this.stopRenderLoop();
  4596. while (this.scenes.length) {
  4597. this.scenes[0].dispose();
  4598. }
  4599. for (var name in this._compiledEffects) {
  4600. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4601. }
  4602. for (var i in this._vertexAttribArrays) {
  4603. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4604. continue;
  4605. }
  4606. this._gl.disableVertexAttribArray(i);
  4607. }
  4608. // Events
  4609. window.removeEventListener("blur", this._onBlur);
  4610. window.removeEventListener("focus", this._onFocus);
  4611. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4612. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4613. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4614. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4615. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4616. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4617. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4618. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4619. };
  4620. // Loading screen
  4621. Engine.prototype.displayLoadingUI = function () {
  4622. var _this = this;
  4623. this._loadingDiv = document.createElement("div");
  4624. this._loadingDiv.style.opacity = "0";
  4625. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4626. // Loading text
  4627. this._loadingTextDiv = document.createElement("div");
  4628. this._loadingTextDiv.style.position = "absolute";
  4629. this._loadingTextDiv.style.left = "0";
  4630. this._loadingTextDiv.style.top = "50%";
  4631. this._loadingTextDiv.style.marginTop = "80px";
  4632. this._loadingTextDiv.style.width = "100%";
  4633. this._loadingTextDiv.style.height = "20px";
  4634. this._loadingTextDiv.style.fontFamily = "Arial";
  4635. this._loadingTextDiv.style.fontSize = "14px";
  4636. this._loadingTextDiv.style.color = "white";
  4637. this._loadingTextDiv.style.textAlign = "center";
  4638. this._loadingTextDiv.innerHTML = "Loading";
  4639. this._loadingDiv.appendChild(this._loadingTextDiv);
  4640. // Loading img
  4641. var imgBack = new Image();
  4642. 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==";
  4643. imgBack.style.position = "absolute";
  4644. imgBack.style.left = "50%";
  4645. imgBack.style.top = "50%";
  4646. imgBack.style.marginLeft = "-50px";
  4647. imgBack.style.marginTop = "-50px";
  4648. imgBack.style.transition = "transform 1.0s ease";
  4649. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4650. var deg = 360;
  4651. var onTransitionEnd = function () {
  4652. deg += 360;
  4653. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4654. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4655. };
  4656. imgBack.addEventListener("transitionend", onTransitionEnd);
  4657. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4658. this._loadingDiv.appendChild(imgBack);
  4659. // front image
  4660. var imgFront = new Image();
  4661. 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=";
  4662. imgFront.style.position = "absolute";
  4663. imgFront.style.left = "50%";
  4664. imgFront.style.top = "50%";
  4665. imgFront.style.marginLeft = "-50px";
  4666. imgFront.style.marginTop = "-50px";
  4667. this._loadingDiv.appendChild(imgFront);
  4668. // Resize
  4669. this._resizeLoadingUI = function () {
  4670. var canvasRect = _this.getRenderingCanvasClientRect();
  4671. _this._loadingDiv.style.position = "absolute";
  4672. _this._loadingDiv.style.left = canvasRect.left + "px";
  4673. _this._loadingDiv.style.top = canvasRect.top + "px";
  4674. _this._loadingDiv.style.width = canvasRect.width + "px";
  4675. _this._loadingDiv.style.height = canvasRect.height + "px";
  4676. };
  4677. this._resizeLoadingUI();
  4678. window.addEventListener("resize", this._resizeLoadingUI);
  4679. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4680. document.body.appendChild(this._loadingDiv);
  4681. setTimeout(function () {
  4682. _this._loadingDiv.style.opacity = "1";
  4683. imgBack.style.transform = "rotateZ(360deg)";
  4684. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4685. }, 0);
  4686. };
  4687. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4688. set: function (text) {
  4689. if (!this._loadingDiv) {
  4690. return;
  4691. }
  4692. this._loadingTextDiv.innerHTML = text;
  4693. },
  4694. enumerable: true,
  4695. configurable: true
  4696. });
  4697. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4698. get: function () {
  4699. return this._loadingDivBackgroundColor;
  4700. },
  4701. set: function (color) {
  4702. this._loadingDivBackgroundColor = color;
  4703. if (!this._loadingDiv) {
  4704. return;
  4705. }
  4706. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4707. },
  4708. enumerable: true,
  4709. configurable: true
  4710. });
  4711. Engine.prototype.hideLoadingUI = function () {
  4712. var _this = this;
  4713. if (!this._loadingDiv) {
  4714. return;
  4715. }
  4716. var onTransitionEnd = function () {
  4717. if (!_this._loadingDiv) {
  4718. return;
  4719. }
  4720. document.body.removeChild(_this._loadingDiv);
  4721. window.removeEventListener("resize", _this._resizeLoadingUI);
  4722. _this._loadingDiv = null;
  4723. };
  4724. this._loadingDiv.style.opacity = "0";
  4725. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4726. };
  4727. // FPS
  4728. Engine.prototype.getFps = function () {
  4729. return this.fps;
  4730. };
  4731. Engine.prototype.getDeltaTime = function () {
  4732. return this.deltaTime;
  4733. };
  4734. Engine.prototype._measureFps = function () {
  4735. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4736. var length = this.previousFramesDuration.length;
  4737. if (length >= 2) {
  4738. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4739. }
  4740. if (length >= this.fpsRange) {
  4741. if (length > this.fpsRange) {
  4742. this.previousFramesDuration.splice(0, 1);
  4743. length = this.previousFramesDuration.length;
  4744. }
  4745. var sum = 0;
  4746. for (var id = 0; id < length - 1; id++) {
  4747. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4748. }
  4749. this.fps = 1000.0 / (sum / (length - 1));
  4750. }
  4751. };
  4752. // Statics
  4753. Engine.isSupported = function () {
  4754. try {
  4755. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4756. if (navigator.isCocoonJS) {
  4757. return true;
  4758. }
  4759. var tempcanvas = document.createElement("canvas");
  4760. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4761. return gl != null && !!window.WebGLRenderingContext;
  4762. } catch (e) {
  4763. return false;
  4764. }
  4765. };
  4766. Engine._ALPHA_DISABLE = 0;
  4767. Engine._ALPHA_ADD = 1;
  4768. Engine._ALPHA_COMBINE = 2;
  4769. Engine._DELAYLOADSTATE_NONE = 0;
  4770. Engine._DELAYLOADSTATE_LOADED = 1;
  4771. Engine._DELAYLOADSTATE_LOADING = 2;
  4772. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4773. Engine._TEXTUREFORMAT_ALPHA = 0;
  4774. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4775. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4776. Engine._TEXTUREFORMAT_RGB = 4;
  4777. Engine._TEXTUREFORMAT_RGBA = 4;
  4778. Engine.Epsilon = 0.001;
  4779. Engine.CollisionsEpsilon = 0.001;
  4780. Engine.ShadersRepository = "Babylon/Shaders/";
  4781. return Engine;
  4782. })();
  4783. BABYLON.Engine = Engine;
  4784. })(BABYLON || (BABYLON = {}));
  4785. //# sourceMappingURL=babylon.engine.js.map
  4786. var BABYLON;
  4787. (function (BABYLON) {
  4788. var Node = (function () {
  4789. function Node(name, scene) {
  4790. this.state = "";
  4791. this.animations = new Array();
  4792. this._childrenFlag = -1;
  4793. this._isEnabled = true;
  4794. this._isReady = true;
  4795. this._currentRenderId = -1;
  4796. this.name = name;
  4797. this.id = name;
  4798. this._scene = scene;
  4799. this._initCache();
  4800. }
  4801. Node.prototype.getScene = function () {
  4802. return this._scene;
  4803. };
  4804. Node.prototype.getEngine = function () {
  4805. return this._scene.getEngine();
  4806. };
  4807. // override it in derived class
  4808. Node.prototype.getWorldMatrix = function () {
  4809. return BABYLON.Matrix.Identity();
  4810. };
  4811. // override it in derived class if you add new variables to the cache
  4812. // and call the parent class method
  4813. Node.prototype._initCache = function () {
  4814. this._cache = {};
  4815. this._cache.parent = undefined;
  4816. };
  4817. Node.prototype.updateCache = function (force) {
  4818. if (!force && this.isSynchronized())
  4819. return;
  4820. this._cache.parent = this.parent;
  4821. this._updateCache();
  4822. };
  4823. // override it in derived class if you add new variables to the cache
  4824. // and call the parent class method if !ignoreParentClass
  4825. Node.prototype._updateCache = function (ignoreParentClass) {
  4826. };
  4827. // override it in derived class if you add new variables to the cache
  4828. Node.prototype._isSynchronized = function () {
  4829. return true;
  4830. };
  4831. Node.prototype.isSynchronizedWithParent = function () {
  4832. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4833. };
  4834. Node.prototype.isSynchronized = function (updateCache) {
  4835. var check = this.hasNewParent();
  4836. check = check || !this.isSynchronizedWithParent();
  4837. check = check || !this._isSynchronized();
  4838. if (updateCache)
  4839. this.updateCache(true);
  4840. return !check;
  4841. };
  4842. Node.prototype.hasNewParent = function (update) {
  4843. if (this._cache.parent === this.parent)
  4844. return false;
  4845. if (update)
  4846. this._cache.parent = this.parent;
  4847. return true;
  4848. };
  4849. Node.prototype.isReady = function () {
  4850. return this._isReady;
  4851. };
  4852. Node.prototype.isEnabled = function () {
  4853. if (!this._isEnabled) {
  4854. return false;
  4855. }
  4856. if (this.parent) {
  4857. return this.parent.isEnabled();
  4858. }
  4859. return true;
  4860. };
  4861. Node.prototype.setEnabled = function (value) {
  4862. this._isEnabled = value;
  4863. };
  4864. Node.prototype.isDescendantOf = function (ancestor) {
  4865. if (this.parent) {
  4866. if (this.parent === ancestor) {
  4867. return true;
  4868. }
  4869. return this.parent.isDescendantOf(ancestor);
  4870. }
  4871. return false;
  4872. };
  4873. Node.prototype._getDescendants = function (list, results) {
  4874. for (var index = 0; index < list.length; index++) {
  4875. var item = list[index];
  4876. if (item.isDescendantOf(this)) {
  4877. results.push(item);
  4878. }
  4879. }
  4880. };
  4881. Node.prototype.getDescendants = function () {
  4882. var results = [];
  4883. this._getDescendants(this._scene.meshes, results);
  4884. this._getDescendants(this._scene.lights, results);
  4885. this._getDescendants(this._scene.cameras, results);
  4886. return results;
  4887. };
  4888. Node.prototype._setReady = function (state) {
  4889. if (state == this._isReady) {
  4890. return;
  4891. }
  4892. if (!state) {
  4893. this._isReady = false;
  4894. return;
  4895. }
  4896. this._isReady = true;
  4897. if (this.onReady) {
  4898. this.onReady(this);
  4899. }
  4900. };
  4901. return Node;
  4902. })();
  4903. BABYLON.Node = Node;
  4904. })(BABYLON || (BABYLON = {}));
  4905. //# sourceMappingURL=babylon.node.js.map
  4906. var BABYLON;
  4907. (function (BABYLON) {
  4908. var BoundingSphere = (function () {
  4909. function BoundingSphere(minimum, maximum) {
  4910. this.minimum = minimum;
  4911. this.maximum = maximum;
  4912. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4913. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4914. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4915. this.radius = distance * 0.5;
  4916. this.centerWorld = BABYLON.Vector3.Zero();
  4917. this._update(BABYLON.Matrix.Identity());
  4918. }
  4919. // Methods
  4920. BoundingSphere.prototype._update = function (world) {
  4921. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4922. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4923. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4924. };
  4925. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4926. for (var i = 0; i < 6; i++) {
  4927. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4928. return false;
  4929. }
  4930. return true;
  4931. };
  4932. BoundingSphere.prototype.intersectsPoint = function (point) {
  4933. var x = this.centerWorld.x - point.x;
  4934. var y = this.centerWorld.y - point.y;
  4935. var z = this.centerWorld.z - point.z;
  4936. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4937. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4938. return false;
  4939. return true;
  4940. };
  4941. // Statics
  4942. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4943. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4944. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4945. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4946. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4947. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4948. return false;
  4949. return true;
  4950. };
  4951. return BoundingSphere;
  4952. })();
  4953. BABYLON.BoundingSphere = BoundingSphere;
  4954. })(BABYLON || (BABYLON = {}));
  4955. //# sourceMappingURL=babylon.boundingSphere.js.map
  4956. var BABYLON;
  4957. (function (BABYLON) {
  4958. var BoundingBox = (function () {
  4959. function BoundingBox(minimum, maximum) {
  4960. this.minimum = minimum;
  4961. this.maximum = maximum;
  4962. this.vectors = new Array();
  4963. this.vectorsWorld = new Array();
  4964. // Bounding vectors
  4965. this.vectors.push(this.minimum.clone());
  4966. this.vectors.push(this.maximum.clone());
  4967. this.vectors.push(this.minimum.clone());
  4968. this.vectors[2].x = this.maximum.x;
  4969. this.vectors.push(this.minimum.clone());
  4970. this.vectors[3].y = this.maximum.y;
  4971. this.vectors.push(this.minimum.clone());
  4972. this.vectors[4].z = this.maximum.z;
  4973. this.vectors.push(this.maximum.clone());
  4974. this.vectors[5].z = this.minimum.z;
  4975. this.vectors.push(this.maximum.clone());
  4976. this.vectors[6].x = this.minimum.x;
  4977. this.vectors.push(this.maximum.clone());
  4978. this.vectors[7].y = this.minimum.y;
  4979. // OBB
  4980. this.center = this.maximum.add(this.minimum).scale(0.5);
  4981. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4982. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4983. for (var index = 0; index < this.vectors.length; index++) {
  4984. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4985. }
  4986. this.minimumWorld = BABYLON.Vector3.Zero();
  4987. this.maximumWorld = BABYLON.Vector3.Zero();
  4988. this._update(BABYLON.Matrix.Identity());
  4989. }
  4990. // Methods
  4991. BoundingBox.prototype.getWorldMatrix = function () {
  4992. return this._worldMatrix;
  4993. };
  4994. BoundingBox.prototype._update = function (world) {
  4995. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4996. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4997. for (var index = 0; index < this.vectors.length; index++) {
  4998. var v = this.vectorsWorld[index];
  4999. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5000. if (v.x < this.minimumWorld.x)
  5001. this.minimumWorld.x = v.x;
  5002. if (v.y < this.minimumWorld.y)
  5003. this.minimumWorld.y = v.y;
  5004. if (v.z < this.minimumWorld.z)
  5005. this.minimumWorld.z = v.z;
  5006. if (v.x > this.maximumWorld.x)
  5007. this.maximumWorld.x = v.x;
  5008. if (v.y > this.maximumWorld.y)
  5009. this.maximumWorld.y = v.y;
  5010. if (v.z > this.maximumWorld.z)
  5011. this.maximumWorld.z = v.z;
  5012. }
  5013. // OBB
  5014. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5015. this.center.scaleInPlace(0.5);
  5016. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5017. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5018. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5019. this._worldMatrix = world;
  5020. };
  5021. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5022. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5023. };
  5024. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5025. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5026. };
  5027. BoundingBox.prototype.intersectsPoint = function (point) {
  5028. var delta = BABYLON.Engine.Epsilon;
  5029. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5030. return false;
  5031. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5032. return false;
  5033. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5034. return false;
  5035. return true;
  5036. };
  5037. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5038. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5039. };
  5040. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5041. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5042. return false;
  5043. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5044. return false;
  5045. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5046. return false;
  5047. return true;
  5048. };
  5049. // Statics
  5050. BoundingBox.Intersects = function (box0, box1) {
  5051. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5052. return false;
  5053. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5054. return false;
  5055. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5056. return false;
  5057. return true;
  5058. };
  5059. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5060. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5061. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5062. return (num <= (sphereRadius * sphereRadius));
  5063. };
  5064. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5065. for (var p = 0; p < 6; p++) {
  5066. for (var i = 0; i < 8; i++) {
  5067. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5068. return false;
  5069. }
  5070. }
  5071. }
  5072. return true;
  5073. };
  5074. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5075. for (var p = 0; p < 6; p++) {
  5076. var inCount = 8;
  5077. for (var i = 0; i < 8; i++) {
  5078. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5079. --inCount;
  5080. } else {
  5081. break;
  5082. }
  5083. }
  5084. if (inCount == 0)
  5085. return false;
  5086. }
  5087. return true;
  5088. };
  5089. return BoundingBox;
  5090. })();
  5091. BABYLON.BoundingBox = BoundingBox;
  5092. })(BABYLON || (BABYLON = {}));
  5093. //# sourceMappingURL=babylon.boundingBox.js.map
  5094. var BABYLON;
  5095. (function (BABYLON) {
  5096. var computeBoxExtents = function (axis, box) {
  5097. var p = BABYLON.Vector3.Dot(box.center, axis);
  5098. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5099. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5100. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5101. var r = r0 + r1 + r2;
  5102. return {
  5103. min: p - r,
  5104. max: p + r
  5105. };
  5106. };
  5107. var extentsOverlap = function (min0, max0, min1, max1) {
  5108. return !(min0 > max1 || min1 > max0);
  5109. };
  5110. var axisOverlap = function (axis, box0, box1) {
  5111. var result0 = computeBoxExtents(axis, box0);
  5112. var result1 = computeBoxExtents(axis, box1);
  5113. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5114. };
  5115. var BoundingInfo = (function () {
  5116. function BoundingInfo(minimum, maximum) {
  5117. this.minimum = minimum;
  5118. this.maximum = maximum;
  5119. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5120. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5121. }
  5122. // Methods
  5123. BoundingInfo.prototype._update = function (world) {
  5124. this.boundingBox._update(world);
  5125. this.boundingSphere._update(world);
  5126. };
  5127. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5128. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5129. return false;
  5130. return this.boundingBox.isInFrustum(frustumPlanes);
  5131. };
  5132. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5133. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5134. };
  5135. BoundingInfo.prototype._checkCollision = function (collider) {
  5136. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5137. };
  5138. BoundingInfo.prototype.intersectsPoint = function (point) {
  5139. if (!this.boundingSphere.centerWorld) {
  5140. return false;
  5141. }
  5142. if (!this.boundingSphere.intersectsPoint(point)) {
  5143. return false;
  5144. }
  5145. if (!this.boundingBox.intersectsPoint(point)) {
  5146. return false;
  5147. }
  5148. return true;
  5149. };
  5150. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5151. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5152. return false;
  5153. }
  5154. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5155. return false;
  5156. }
  5157. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5158. return false;
  5159. }
  5160. if (!precise) {
  5161. return true;
  5162. }
  5163. var box0 = this.boundingBox;
  5164. var box1 = boundingInfo.boundingBox;
  5165. if (!axisOverlap(box0.directions[0], box0, box1))
  5166. return false;
  5167. if (!axisOverlap(box0.directions[1], box0, box1))
  5168. return false;
  5169. if (!axisOverlap(box0.directions[2], box0, box1))
  5170. return false;
  5171. if (!axisOverlap(box1.directions[0], box0, box1))
  5172. return false;
  5173. if (!axisOverlap(box1.directions[1], box0, box1))
  5174. return false;
  5175. if (!axisOverlap(box1.directions[2], box0, box1))
  5176. return false;
  5177. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5178. return false;
  5179. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5180. return false;
  5181. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5182. return false;
  5183. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5184. return false;
  5185. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5186. return false;
  5187. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5188. return false;
  5189. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5190. return false;
  5191. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5192. return false;
  5193. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5194. return false;
  5195. return true;
  5196. };
  5197. return BoundingInfo;
  5198. })();
  5199. BABYLON.BoundingInfo = BoundingInfo;
  5200. })(BABYLON || (BABYLON = {}));
  5201. //# sourceMappingURL=babylon.boundingInfo.js.map
  5202. var BABYLON;
  5203. (function (BABYLON) {
  5204. var Light = (function (_super) {
  5205. __extends(Light, _super);
  5206. function Light(name, scene) {
  5207. _super.call(this, name, scene);
  5208. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5209. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5210. this.intensity = 1.0;
  5211. this.range = Number.MAX_VALUE;
  5212. this.includedOnlyMeshes = new Array();
  5213. this.excludedMeshes = new Array();
  5214. this._excludedMeshesIds = new Array();
  5215. this._includedOnlyMeshesIds = new Array();
  5216. scene.lights.push(this);
  5217. }
  5218. Light.prototype.getShadowGenerator = function () {
  5219. return this._shadowGenerator;
  5220. };
  5221. Light.prototype.getAbsolutePosition = function () {
  5222. return BABYLON.Vector3.Zero();
  5223. };
  5224. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5225. };
  5226. Light.prototype._getWorldMatrix = function () {
  5227. return BABYLON.Matrix.Identity();
  5228. };
  5229. Light.prototype.canAffectMesh = function (mesh) {
  5230. if (!mesh) {
  5231. return true;
  5232. }
  5233. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5234. return false;
  5235. }
  5236. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5237. return false;
  5238. }
  5239. return true;
  5240. };
  5241. Light.prototype.getWorldMatrix = function () {
  5242. this._currentRenderId = this.getScene().getRenderId();
  5243. var worldMatrix = this._getWorldMatrix();
  5244. if (this.parent && this.parent.getWorldMatrix) {
  5245. if (!this._parentedWorldMatrix) {
  5246. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5247. }
  5248. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5249. return this._parentedWorldMatrix;
  5250. }
  5251. return worldMatrix;
  5252. };
  5253. Light.prototype.dispose = function () {
  5254. if (this._shadowGenerator) {
  5255. this._shadowGenerator.dispose();
  5256. this._shadowGenerator = null;
  5257. }
  5258. // Remove from scene
  5259. var index = this.getScene().lights.indexOf(this);
  5260. this.getScene().lights.splice(index, 1);
  5261. };
  5262. return Light;
  5263. })(BABYLON.Node);
  5264. BABYLON.Light = Light;
  5265. })(BABYLON || (BABYLON = {}));
  5266. //# sourceMappingURL=babylon.light.js.map
  5267. var BABYLON;
  5268. (function (BABYLON) {
  5269. var PointLight = (function (_super) {
  5270. __extends(PointLight, _super);
  5271. function PointLight(name, position, scene) {
  5272. _super.call(this, name, scene);
  5273. this.position = position;
  5274. }
  5275. PointLight.prototype.getAbsolutePosition = function () {
  5276. return this._transformedPosition ? this._transformedPosition : this.position;
  5277. };
  5278. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5279. if (this.parent && this.parent.getWorldMatrix) {
  5280. if (!this._transformedPosition) {
  5281. this._transformedPosition = BABYLON.Vector3.Zero();
  5282. }
  5283. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5284. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5285. return;
  5286. }
  5287. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5288. };
  5289. PointLight.prototype.getShadowGenerator = function () {
  5290. return null;
  5291. };
  5292. PointLight.prototype._getWorldMatrix = function () {
  5293. if (!this._worldMatrix) {
  5294. this._worldMatrix = BABYLON.Matrix.Identity();
  5295. }
  5296. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5297. return this._worldMatrix;
  5298. };
  5299. return PointLight;
  5300. })(BABYLON.Light);
  5301. BABYLON.PointLight = PointLight;
  5302. })(BABYLON || (BABYLON = {}));
  5303. //# sourceMappingURL=babylon.pointLight.js.map
  5304. var BABYLON;
  5305. (function (BABYLON) {
  5306. var SpotLight = (function (_super) {
  5307. __extends(SpotLight, _super);
  5308. function SpotLight(name, position, direction, angle, exponent, scene) {
  5309. _super.call(this, name, scene);
  5310. this.position = position;
  5311. this.direction = direction;
  5312. this.angle = angle;
  5313. this.exponent = exponent;
  5314. }
  5315. SpotLight.prototype.getAbsolutePosition = function () {
  5316. return this.transformedPosition ? this.transformedPosition : this.position;
  5317. };
  5318. SpotLight.prototype.setDirectionToTarget = function (target) {
  5319. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5320. return this.direction;
  5321. };
  5322. SpotLight.prototype.computeTransformedPosition = function () {
  5323. if (this.parent && this.parent.getWorldMatrix) {
  5324. if (!this.transformedPosition) {
  5325. this.transformedPosition = BABYLON.Vector3.Zero();
  5326. }
  5327. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5328. return true;
  5329. }
  5330. return false;
  5331. };
  5332. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5333. var normalizeDirection;
  5334. if (this.parent && this.parent.getWorldMatrix) {
  5335. if (!this._transformedDirection) {
  5336. this._transformedDirection = BABYLON.Vector3.Zero();
  5337. }
  5338. this.computeTransformedPosition();
  5339. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5340. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5341. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5342. } else {
  5343. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5344. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5345. }
  5346. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5347. };
  5348. SpotLight.prototype._getWorldMatrix = function () {
  5349. if (!this._worldMatrix) {
  5350. this._worldMatrix = BABYLON.Matrix.Identity();
  5351. }
  5352. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5353. return this._worldMatrix;
  5354. };
  5355. return SpotLight;
  5356. })(BABYLON.Light);
  5357. BABYLON.SpotLight = SpotLight;
  5358. })(BABYLON || (BABYLON = {}));
  5359. //# sourceMappingURL=babylon.spotLight.js.map
  5360. var BABYLON;
  5361. (function (BABYLON) {
  5362. var DirectionalLight = (function (_super) {
  5363. __extends(DirectionalLight, _super);
  5364. function DirectionalLight(name, direction, scene) {
  5365. _super.call(this, name, scene);
  5366. this.direction = direction;
  5367. this.position = direction.scale(-1);
  5368. }
  5369. DirectionalLight.prototype.getAbsolutePosition = function () {
  5370. return this.transformedPosition ? this.transformedPosition : this.position;
  5371. };
  5372. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5373. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5374. return this.direction;
  5375. };
  5376. DirectionalLight.prototype.computeTransformedPosition = function () {
  5377. if (this.parent && this.parent.getWorldMatrix) {
  5378. if (!this.transformedPosition) {
  5379. this.transformedPosition = BABYLON.Vector3.Zero();
  5380. }
  5381. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5382. return true;
  5383. }
  5384. return false;
  5385. };
  5386. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5387. if (this.parent && this.parent.getWorldMatrix) {
  5388. if (!this._transformedDirection) {
  5389. this._transformedDirection = BABYLON.Vector3.Zero();
  5390. }
  5391. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5392. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5393. return;
  5394. }
  5395. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5396. };
  5397. DirectionalLight.prototype._getWorldMatrix = function () {
  5398. if (!this._worldMatrix) {
  5399. this._worldMatrix = BABYLON.Matrix.Identity();
  5400. }
  5401. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5402. return this._worldMatrix;
  5403. };
  5404. return DirectionalLight;
  5405. })(BABYLON.Light);
  5406. BABYLON.DirectionalLight = DirectionalLight;
  5407. })(BABYLON || (BABYLON = {}));
  5408. //# sourceMappingURL=babylon.directionalLight.js.map
  5409. var BABYLON;
  5410. (function (BABYLON) {
  5411. var ShadowGenerator = (function () {
  5412. function ShadowGenerator(mapSize, light) {
  5413. var _this = this;
  5414. // Members
  5415. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5416. this._darkness = 0;
  5417. this._transparencyShadow = false;
  5418. this._viewMatrix = BABYLON.Matrix.Zero();
  5419. this._projectionMatrix = BABYLON.Matrix.Zero();
  5420. this._transformMatrix = BABYLON.Matrix.Zero();
  5421. this._worldViewProjection = BABYLON.Matrix.Zero();
  5422. this._light = light;
  5423. this._scene = light.getScene();
  5424. light._shadowGenerator = this;
  5425. // Render target
  5426. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5427. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5428. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5429. this._shadowMap.renderParticles = false;
  5430. // Custom render function
  5431. var renderSubMesh = function (subMesh) {
  5432. var mesh = subMesh.getRenderingMesh();
  5433. var scene = _this._scene;
  5434. var engine = scene.getEngine();
  5435. // Culling
  5436. engine.setState(subMesh.getMaterial().backFaceCulling);
  5437. // Managing instances
  5438. var batch = mesh._getInstancesRenderList(subMesh._id);
  5439. if (batch.mustReturn) {
  5440. return;
  5441. }
  5442. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5443. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5444. engine.enableEffect(_this._effect);
  5445. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5446. var material = subMesh.getMaterial();
  5447. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5448. // Alpha test
  5449. if (material && material.needAlphaTesting()) {
  5450. var alphaTexture = material.getAlphaTestTexture();
  5451. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5452. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5453. }
  5454. // Bones
  5455. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5456. if (useBones) {
  5457. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5458. }
  5459. if (hardwareInstancedRendering) {
  5460. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5461. } else {
  5462. if (batch.renderSelf[subMesh._id]) {
  5463. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5464. // Draw
  5465. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5466. }
  5467. if (batch.visibleInstances[subMesh._id]) {
  5468. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5469. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5470. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5471. // Draw
  5472. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5473. }
  5474. }
  5475. }
  5476. } else {
  5477. // Need to reset refresh rate of the shadowMap
  5478. _this._shadowMap.resetRefreshCounter();
  5479. }
  5480. };
  5481. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5482. var index;
  5483. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5484. renderSubMesh(opaqueSubMeshes.data[index]);
  5485. }
  5486. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5487. renderSubMesh(alphaTestSubMeshes.data[index]);
  5488. }
  5489. if (_this._transparencyShadow) {
  5490. for (index = 0; index < transparentSubMeshes.length; index++) {
  5491. renderSubMesh(transparentSubMeshes.data[index]);
  5492. }
  5493. }
  5494. };
  5495. }
  5496. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5497. // Static
  5498. get: function () {
  5499. return ShadowGenerator._FILTER_NONE;
  5500. },
  5501. enumerable: true,
  5502. configurable: true
  5503. });
  5504. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5505. get: function () {
  5506. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5507. },
  5508. enumerable: true,
  5509. configurable: true
  5510. });
  5511. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5512. get: function () {
  5513. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5514. },
  5515. enumerable: true,
  5516. configurable: true
  5517. });
  5518. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5519. get: function () {
  5520. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5521. },
  5522. set: function (value) {
  5523. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5524. },
  5525. enumerable: true,
  5526. configurable: true
  5527. });
  5528. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5529. get: function () {
  5530. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5531. },
  5532. set: function (value) {
  5533. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5534. },
  5535. enumerable: true,
  5536. configurable: true
  5537. });
  5538. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5539. var defines = [];
  5540. if (this.useVarianceShadowMap) {
  5541. defines.push("#define VSM");
  5542. }
  5543. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5544. var mesh = subMesh.getMesh();
  5545. var scene = mesh.getScene();
  5546. var material = subMesh.getMaterial();
  5547. // Alpha test
  5548. if (material && material.needAlphaTesting()) {
  5549. defines.push("#define ALPHATEST");
  5550. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5551. attribs.push(BABYLON.VertexBuffer.UVKind);
  5552. defines.push("#define UV1");
  5553. }
  5554. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5555. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5556. defines.push("#define UV2");
  5557. }
  5558. }
  5559. // Bones
  5560. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5561. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5562. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5563. defines.push("#define BONES");
  5564. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5565. }
  5566. // Instances
  5567. if (useInstances) {
  5568. defines.push("#define INSTANCES");
  5569. attribs.push("world0");
  5570. attribs.push("world1");
  5571. attribs.push("world2");
  5572. attribs.push("world3");
  5573. }
  5574. // Get correct effect
  5575. var join = defines.join("\n");
  5576. if (this._cachedDefines !== join) {
  5577. this._cachedDefines = join;
  5578. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5579. }
  5580. return this._effect.isReady();
  5581. };
  5582. ShadowGenerator.prototype.getShadowMap = function () {
  5583. return this._shadowMap;
  5584. };
  5585. ShadowGenerator.prototype.getLight = function () {
  5586. return this._light;
  5587. };
  5588. // Methods
  5589. ShadowGenerator.prototype.getTransformMatrix = function () {
  5590. var lightPosition = this._light.position;
  5591. var lightDirection = this._light.direction;
  5592. if (this._light.computeTransformedPosition()) {
  5593. lightPosition = this._light.transformedPosition;
  5594. }
  5595. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5596. this._cachedPosition = lightPosition.clone();
  5597. this._cachedDirection = lightDirection.clone();
  5598. var activeCamera = this._scene.activeCamera;
  5599. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5600. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5601. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5602. }
  5603. return this._transformMatrix;
  5604. };
  5605. ShadowGenerator.prototype.getDarkness = function () {
  5606. return this._darkness;
  5607. };
  5608. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5609. if (darkness >= 1.0)
  5610. this._darkness = 1.0;
  5611. else if (darkness <= 0.0)
  5612. this._darkness = 0.0;
  5613. else
  5614. this._darkness = darkness;
  5615. };
  5616. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5617. this._transparencyShadow = hasShadow;
  5618. };
  5619. ShadowGenerator.prototype.dispose = function () {
  5620. this._shadowMap.dispose();
  5621. };
  5622. ShadowGenerator._FILTER_NONE = 0;
  5623. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5624. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5625. return ShadowGenerator;
  5626. })();
  5627. BABYLON.ShadowGenerator = ShadowGenerator;
  5628. })(BABYLON || (BABYLON = {}));
  5629. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5630. var BABYLON;
  5631. (function (BABYLON) {
  5632. var HemisphericLight = (function (_super) {
  5633. __extends(HemisphericLight, _super);
  5634. function HemisphericLight(name, direction, scene) {
  5635. _super.call(this, name, scene);
  5636. this.direction = direction;
  5637. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5638. }
  5639. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5640. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5641. return this.direction;
  5642. };
  5643. HemisphericLight.prototype.getShadowGenerator = function () {
  5644. return null;
  5645. };
  5646. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5647. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5648. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5649. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5650. };
  5651. HemisphericLight.prototype._getWorldMatrix = function () {
  5652. if (!this._worldMatrix) {
  5653. this._worldMatrix = BABYLON.Matrix.Identity();
  5654. }
  5655. return this._worldMatrix;
  5656. };
  5657. return HemisphericLight;
  5658. })(BABYLON.Light);
  5659. BABYLON.HemisphericLight = HemisphericLight;
  5660. })(BABYLON || (BABYLON = {}));
  5661. //# sourceMappingURL=babylon.hemisphericLight.js.map
  5662. var BABYLON;
  5663. (function (BABYLON) {
  5664. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5665. if (boxMin.x > sphereCenter.x + sphereRadius)
  5666. return false;
  5667. if (sphereCenter.x - sphereRadius > boxMax.x)
  5668. return false;
  5669. if (boxMin.y > sphereCenter.y + sphereRadius)
  5670. return false;
  5671. if (sphereCenter.y - sphereRadius > boxMax.y)
  5672. return false;
  5673. if (boxMin.z > sphereCenter.z + sphereRadius)
  5674. return false;
  5675. if (sphereCenter.z - sphereRadius > boxMax.z)
  5676. return false;
  5677. return true;
  5678. };
  5679. var getLowestRoot = function (a, b, c, maxR) {
  5680. var determinant = b * b - 4.0 * a * c;
  5681. var result = { root: 0, found: false };
  5682. if (determinant < 0)
  5683. return result;
  5684. var sqrtD = Math.sqrt(determinant);
  5685. var r1 = (-b - sqrtD) / (2.0 * a);
  5686. var r2 = (-b + sqrtD) / (2.0 * a);
  5687. if (r1 > r2) {
  5688. var temp = r2;
  5689. r2 = r1;
  5690. r1 = temp;
  5691. }
  5692. if (r1 > 0 && r1 < maxR) {
  5693. result.root = r1;
  5694. result.found = true;
  5695. return result;
  5696. }
  5697. if (r2 > 0 && r2 < maxR) {
  5698. result.root = r2;
  5699. result.found = true;
  5700. return result;
  5701. }
  5702. return result;
  5703. };
  5704. var Collider = (function () {
  5705. function Collider() {
  5706. this.radius = new BABYLON.Vector3(1, 1, 1);
  5707. this.retry = 0;
  5708. this.basePointWorld = BABYLON.Vector3.Zero();
  5709. this.velocityWorld = BABYLON.Vector3.Zero();
  5710. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5711. this._collisionPoint = BABYLON.Vector3.Zero();
  5712. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5713. this._tempVector = BABYLON.Vector3.Zero();
  5714. this._tempVector2 = BABYLON.Vector3.Zero();
  5715. this._tempVector3 = BABYLON.Vector3.Zero();
  5716. this._tempVector4 = BABYLON.Vector3.Zero();
  5717. this._edge = BABYLON.Vector3.Zero();
  5718. this._baseToVertex = BABYLON.Vector3.Zero();
  5719. this._destinationPoint = BABYLON.Vector3.Zero();
  5720. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5721. this._displacementVector = BABYLON.Vector3.Zero();
  5722. }
  5723. // Methods
  5724. Collider.prototype._initialize = function (source, dir, e) {
  5725. this.velocity = dir;
  5726. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5727. this.basePoint = source;
  5728. source.multiplyToRef(this.radius, this.basePointWorld);
  5729. dir.multiplyToRef(this.radius, this.velocityWorld);
  5730. this.velocityWorldLength = this.velocityWorld.length();
  5731. this.epsilon = e;
  5732. this.collisionFound = false;
  5733. };
  5734. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5735. pa.subtractToRef(point, this._tempVector);
  5736. pb.subtractToRef(point, this._tempVector2);
  5737. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5738. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5739. if (d < 0)
  5740. return false;
  5741. pc.subtractToRef(point, this._tempVector3);
  5742. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5743. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5744. if (d < 0)
  5745. return false;
  5746. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5747. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5748. return d >= 0;
  5749. };
  5750. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5751. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5752. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5753. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5754. return false;
  5755. }
  5756. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5757. return false;
  5758. return true;
  5759. };
  5760. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5761. var t0;
  5762. var embeddedInPlane = false;
  5763. if (!subMesh._trianglePlanes) {
  5764. subMesh._trianglePlanes = [];
  5765. }
  5766. if (!subMesh._trianglePlanes[faceIndex]) {
  5767. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5768. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5769. }
  5770. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5771. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5772. return;
  5773. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5774. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5775. if (normalDotVelocity == 0) {
  5776. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5777. return;
  5778. embeddedInPlane = true;
  5779. t0 = 0;
  5780. } else {
  5781. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5782. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5783. if (t0 > t1) {
  5784. var temp = t1;
  5785. t1 = t0;
  5786. t0 = temp;
  5787. }
  5788. if (t0 > 1.0 || t1 < 0.0)
  5789. return;
  5790. if (t0 < 0)
  5791. t0 = 0;
  5792. if (t0 > 1.0)
  5793. t0 = 1.0;
  5794. }
  5795. this._collisionPoint.copyFromFloats(0, 0, 0);
  5796. var found = false;
  5797. var t = 1.0;
  5798. if (!embeddedInPlane) {
  5799. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5800. this.velocity.scaleToRef(t0, this._tempVector);
  5801. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5802. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5803. found = true;
  5804. t = t0;
  5805. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5806. }
  5807. }
  5808. if (!found) {
  5809. var velocitySquaredLength = this.velocity.lengthSquared();
  5810. var a = velocitySquaredLength;
  5811. this.basePoint.subtractToRef(p1, this._tempVector);
  5812. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5813. var c = this._tempVector.lengthSquared() - 1.0;
  5814. var lowestRoot = getLowestRoot(a, b, c, t);
  5815. if (lowestRoot.found) {
  5816. t = lowestRoot.root;
  5817. found = true;
  5818. this._collisionPoint.copyFrom(p1);
  5819. }
  5820. this.basePoint.subtractToRef(p2, this._tempVector);
  5821. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5822. c = this._tempVector.lengthSquared() - 1.0;
  5823. lowestRoot = getLowestRoot(a, b, c, t);
  5824. if (lowestRoot.found) {
  5825. t = lowestRoot.root;
  5826. found = true;
  5827. this._collisionPoint.copyFrom(p2);
  5828. }
  5829. this.basePoint.subtractToRef(p3, this._tempVector);
  5830. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5831. c = this._tempVector.lengthSquared() - 1.0;
  5832. lowestRoot = getLowestRoot(a, b, c, t);
  5833. if (lowestRoot.found) {
  5834. t = lowestRoot.root;
  5835. found = true;
  5836. this._collisionPoint.copyFrom(p3);
  5837. }
  5838. p2.subtractToRef(p1, this._edge);
  5839. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5840. var edgeSquaredLength = this._edge.lengthSquared();
  5841. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5842. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5843. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5844. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5845. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5846. lowestRoot = getLowestRoot(a, b, c, t);
  5847. if (lowestRoot.found) {
  5848. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5849. if (f >= 0.0 && f <= 1.0) {
  5850. t = lowestRoot.root;
  5851. found = true;
  5852. this._edge.scaleInPlace(f);
  5853. p1.addToRef(this._edge, this._collisionPoint);
  5854. }
  5855. }
  5856. p3.subtractToRef(p2, this._edge);
  5857. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5858. edgeSquaredLength = this._edge.lengthSquared();
  5859. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5860. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5861. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5862. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5863. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5864. lowestRoot = getLowestRoot(a, b, c, t);
  5865. if (lowestRoot.found) {
  5866. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5867. if (f >= 0.0 && f <= 1.0) {
  5868. t = lowestRoot.root;
  5869. found = true;
  5870. this._edge.scaleInPlace(f);
  5871. p2.addToRef(this._edge, this._collisionPoint);
  5872. }
  5873. }
  5874. p1.subtractToRef(p3, this._edge);
  5875. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5876. edgeSquaredLength = this._edge.lengthSquared();
  5877. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5878. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5879. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5880. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5881. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5882. lowestRoot = getLowestRoot(a, b, c, t);
  5883. if (lowestRoot.found) {
  5884. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5885. if (f >= 0.0 && f <= 1.0) {
  5886. t = lowestRoot.root;
  5887. found = true;
  5888. this._edge.scaleInPlace(f);
  5889. p3.addToRef(this._edge, this._collisionPoint);
  5890. }
  5891. }
  5892. }
  5893. if (found) {
  5894. var distToCollision = t * this.velocity.length();
  5895. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5896. if (!this.intersectionPoint) {
  5897. this.intersectionPoint = this._collisionPoint.clone();
  5898. } else {
  5899. this.intersectionPoint.copyFrom(this._collisionPoint);
  5900. }
  5901. this.nearestDistance = distToCollision;
  5902. this.collisionFound = true;
  5903. this.collidedMesh = subMesh.getMesh();
  5904. }
  5905. }
  5906. };
  5907. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5908. for (var i = indexStart; i < indexEnd; i += 3) {
  5909. var p1 = pts[indices[i] - decal];
  5910. var p2 = pts[indices[i + 1] - decal];
  5911. var p3 = pts[indices[i + 2] - decal];
  5912. this._testTriangle(i, subMesh, p3, p2, p1);
  5913. }
  5914. };
  5915. Collider.prototype._getResponse = function (pos, vel) {
  5916. pos.addToRef(vel, this._destinationPoint);
  5917. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5918. this.basePoint.addToRef(vel, pos);
  5919. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5920. this._slidePlaneNormal.normalize();
  5921. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5922. pos.addInPlace(this._displacementVector);
  5923. this.intersectionPoint.addInPlace(this._displacementVector);
  5924. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5925. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5926. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5927. };
  5928. return Collider;
  5929. })();
  5930. BABYLON.Collider = Collider;
  5931. })(BABYLON || (BABYLON = {}));
  5932. //# sourceMappingURL=babylon.collider.js.map
  5933. var BABYLON;
  5934. (function (BABYLON) {
  5935. var Camera = (function (_super) {
  5936. __extends(Camera, _super);
  5937. function Camera(name, position, scene) {
  5938. _super.call(this, name, scene);
  5939. this.position = position;
  5940. // Members
  5941. this.upVector = BABYLON.Vector3.Up();
  5942. this.orthoLeft = null;
  5943. this.orthoRight = null;
  5944. this.orthoBottom = null;
  5945. this.orthoTop = null;
  5946. this.fov = 0.8;
  5947. this.minZ = 1.0;
  5948. this.maxZ = 10000.0;
  5949. this.inertia = 0.9;
  5950. this.mode = Camera.PERSPECTIVE_CAMERA;
  5951. this.isIntermediate = false;
  5952. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5953. this.subCameras = [];
  5954. this.layerMask = 0xFFFFFFFF;
  5955. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5956. this._projectionMatrix = new BABYLON.Matrix();
  5957. this._postProcesses = new Array();
  5958. this._postProcessesTakenIndices = [];
  5959. scene.cameras.push(this);
  5960. if (!scene.activeCamera) {
  5961. scene.activeCamera = this;
  5962. }
  5963. }
  5964. //Cache
  5965. Camera.prototype._initCache = function () {
  5966. _super.prototype._initCache.call(this);
  5967. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5968. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5969. this._cache.mode = undefined;
  5970. this._cache.minZ = undefined;
  5971. this._cache.maxZ = undefined;
  5972. this._cache.fov = undefined;
  5973. this._cache.aspectRatio = undefined;
  5974. this._cache.orthoLeft = undefined;
  5975. this._cache.orthoRight = undefined;
  5976. this._cache.orthoBottom = undefined;
  5977. this._cache.orthoTop = undefined;
  5978. this._cache.renderWidth = undefined;
  5979. this._cache.renderHeight = undefined;
  5980. };
  5981. Camera.prototype._updateCache = function (ignoreParentClass) {
  5982. if (!ignoreParentClass) {
  5983. _super.prototype._updateCache.call(this);
  5984. }
  5985. var engine = this.getEngine();
  5986. this._cache.position.copyFrom(this.position);
  5987. this._cache.upVector.copyFrom(this.upVector);
  5988. this._cache.mode = this.mode;
  5989. this._cache.minZ = this.minZ;
  5990. this._cache.maxZ = this.maxZ;
  5991. this._cache.fov = this.fov;
  5992. this._cache.aspectRatio = engine.getAspectRatio(this);
  5993. this._cache.orthoLeft = this.orthoLeft;
  5994. this._cache.orthoRight = this.orthoRight;
  5995. this._cache.orthoBottom = this.orthoBottom;
  5996. this._cache.orthoTop = this.orthoTop;
  5997. this._cache.renderWidth = engine.getRenderWidth();
  5998. this._cache.renderHeight = engine.getRenderHeight();
  5999. };
  6000. Camera.prototype._updateFromScene = function () {
  6001. this.updateCache();
  6002. this._update();
  6003. };
  6004. // Synchronized
  6005. Camera.prototype._isSynchronized = function () {
  6006. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6007. };
  6008. Camera.prototype._isSynchronizedViewMatrix = function () {
  6009. if (!_super.prototype._isSynchronized.call(this))
  6010. return false;
  6011. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6012. };
  6013. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6014. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6015. if (!check) {
  6016. return false;
  6017. }
  6018. var engine = this.getEngine();
  6019. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6020. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6021. } else {
  6022. 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();
  6023. }
  6024. return check;
  6025. };
  6026. // Controls
  6027. Camera.prototype.attachControl = function (element) {
  6028. };
  6029. Camera.prototype.detachControl = function (element) {
  6030. };
  6031. Camera.prototype._update = function () {
  6032. };
  6033. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6034. if (typeof insertAt === "undefined") { insertAt = null; }
  6035. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6036. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6037. return 0;
  6038. }
  6039. if (insertAt == null || insertAt < 0) {
  6040. this._postProcesses.push(postProcess);
  6041. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6042. return this._postProcesses.length - 1;
  6043. }
  6044. var add = 0;
  6045. if (this._postProcesses[insertAt]) {
  6046. var start = this._postProcesses.length - 1;
  6047. for (var i = start; i >= insertAt + 1; --i) {
  6048. this._postProcesses[i + 1] = this._postProcesses[i];
  6049. }
  6050. add = 1;
  6051. }
  6052. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6053. if (this._postProcessesTakenIndices[i] < insertAt) {
  6054. continue;
  6055. }
  6056. start = this._postProcessesTakenIndices.length - 1;
  6057. for (var j = start; j >= i; --j) {
  6058. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6059. }
  6060. this._postProcessesTakenIndices[i] = insertAt;
  6061. break;
  6062. }
  6063. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6064. this._postProcessesTakenIndices.push(insertAt);
  6065. }
  6066. var result = insertAt + add;
  6067. this._postProcesses[result] = postProcess;
  6068. return result;
  6069. };
  6070. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6071. if (typeof atIndices === "undefined") { atIndices = null; }
  6072. var result = [];
  6073. if (!atIndices) {
  6074. var length = this._postProcesses.length;
  6075. for (var i = 0; i < length; i++) {
  6076. if (this._postProcesses[i] !== postProcess) {
  6077. continue;
  6078. }
  6079. delete this._postProcesses[i];
  6080. var index = this._postProcessesTakenIndices.indexOf(i);
  6081. this._postProcessesTakenIndices.splice(index, 1);
  6082. }
  6083. } else {
  6084. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6085. for (i = 0; i < atIndices.length; i++) {
  6086. var foundPostProcess = this._postProcesses[atIndices[i]];
  6087. if (foundPostProcess !== postProcess) {
  6088. result.push(i);
  6089. continue;
  6090. }
  6091. delete this._postProcesses[atIndices[i]];
  6092. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6093. this._postProcessesTakenIndices.splice(index, 1);
  6094. }
  6095. }
  6096. return result;
  6097. };
  6098. Camera.prototype.getWorldMatrix = function () {
  6099. if (!this._worldMatrix) {
  6100. this._worldMatrix = BABYLON.Matrix.Identity();
  6101. }
  6102. var viewMatrix = this.getViewMatrix();
  6103. viewMatrix.invertToRef(this._worldMatrix);
  6104. return this._worldMatrix;
  6105. };
  6106. Camera.prototype._getViewMatrix = function () {
  6107. return BABYLON.Matrix.Identity();
  6108. };
  6109. Camera.prototype.getViewMatrix = function () {
  6110. this._computedViewMatrix = this._computeViewMatrix();
  6111. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6112. return this._computedViewMatrix;
  6113. }
  6114. if (!this._worldMatrix) {
  6115. this._worldMatrix = BABYLON.Matrix.Identity();
  6116. }
  6117. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6118. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6119. this._computedViewMatrix.invert();
  6120. this._currentRenderId = this.getScene().getRenderId();
  6121. return this._computedViewMatrix;
  6122. };
  6123. Camera.prototype._computeViewMatrix = function (force) {
  6124. if (!force && this._isSynchronizedViewMatrix()) {
  6125. return this._computedViewMatrix;
  6126. }
  6127. this._computedViewMatrix = this._getViewMatrix();
  6128. if (!this.parent || !this.parent.getWorldMatrix) {
  6129. this._currentRenderId = this.getScene().getRenderId();
  6130. }
  6131. return this._computedViewMatrix;
  6132. };
  6133. Camera.prototype.getProjectionMatrix = function (force) {
  6134. if (!force && this._isSynchronizedProjectionMatrix()) {
  6135. return this._projectionMatrix;
  6136. }
  6137. var engine = this.getEngine();
  6138. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6139. if (this.minZ <= 0) {
  6140. this.minZ = 0.1;
  6141. }
  6142. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  6143. return this._projectionMatrix;
  6144. }
  6145. var halfWidth = engine.getRenderWidth() / 2.0;
  6146. var halfHeight = engine.getRenderHeight() / 2.0;
  6147. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6148. return this._projectionMatrix;
  6149. };
  6150. Camera.prototype.dispose = function () {
  6151. // Remove from scene
  6152. var index = this.getScene().cameras.indexOf(this);
  6153. this.getScene().cameras.splice(index, 1);
  6154. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6155. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6156. }
  6157. };
  6158. Camera.PERSPECTIVE_CAMERA = 0;
  6159. Camera.ORTHOGRAPHIC_CAMERA = 1;
  6160. return Camera;
  6161. })(BABYLON.Node);
  6162. BABYLON.Camera = Camera;
  6163. })(BABYLON || (BABYLON = {}));
  6164. //# sourceMappingURL=babylon.camera.js.map
  6165. var BABYLON;
  6166. (function (BABYLON) {
  6167. var TargetCamera = (function (_super) {
  6168. __extends(TargetCamera, _super);
  6169. function TargetCamera(name, position, scene) {
  6170. _super.call(this, name, position, scene);
  6171. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6172. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6173. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6174. this.speed = 2.0;
  6175. this.noRotationConstraint = false;
  6176. this.lockedTarget = null;
  6177. this._currentTarget = BABYLON.Vector3.Zero();
  6178. this._viewMatrix = BABYLON.Matrix.Zero();
  6179. this._camMatrix = BABYLON.Matrix.Zero();
  6180. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6181. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6182. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6183. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6184. this._lookAtTemp = BABYLON.Matrix.Zero();
  6185. this._tempMatrix = BABYLON.Matrix.Zero();
  6186. }
  6187. TargetCamera.prototype._getLockedTargetPosition = function () {
  6188. if (!this.lockedTarget) {
  6189. return null;
  6190. }
  6191. return this.lockedTarget.position || this.lockedTarget;
  6192. };
  6193. // Cache
  6194. TargetCamera.prototype._initCache = function () {
  6195. _super.prototype._initCache.call(this);
  6196. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6197. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6198. };
  6199. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6200. if (!ignoreParentClass) {
  6201. _super.prototype._updateCache.call(this);
  6202. }
  6203. var lockedTargetPosition = this._getLockedTargetPosition();
  6204. if (!lockedTargetPosition) {
  6205. this._cache.lockedTarget = null;
  6206. } else {
  6207. if (!this._cache.lockedTarget) {
  6208. this._cache.lockedTarget = lockedTargetPosition.clone();
  6209. } else {
  6210. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6211. }
  6212. }
  6213. this._cache.rotation.copyFrom(this.rotation);
  6214. };
  6215. // Synchronized
  6216. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6217. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6218. return false;
  6219. }
  6220. var lockedTargetPosition = this._getLockedTargetPosition();
  6221. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6222. };
  6223. // Methods
  6224. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6225. var engine = this.getEngine();
  6226. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6227. };
  6228. // Target
  6229. TargetCamera.prototype.setTarget = function (target) {
  6230. this.upVector.normalize();
  6231. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6232. this._camMatrix.invert();
  6233. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6234. var vDir = target.subtract(this.position);
  6235. if (vDir.x >= 0.0) {
  6236. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6237. } else {
  6238. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6239. }
  6240. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6241. if (isNaN(this.rotation.x)) {
  6242. this.rotation.x = 0;
  6243. }
  6244. if (isNaN(this.rotation.y)) {
  6245. this.rotation.y = 0;
  6246. }
  6247. if (isNaN(this.rotation.z)) {
  6248. this.rotation.z = 0;
  6249. }
  6250. };
  6251. TargetCamera.prototype.getTarget = function () {
  6252. return this._currentTarget;
  6253. };
  6254. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6255. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6256. };
  6257. TargetCamera.prototype._updatePosition = function () {
  6258. this.position.addInPlace(this.cameraDirection);
  6259. };
  6260. TargetCamera.prototype._update = function () {
  6261. var needToMove = this._decideIfNeedsToMove();
  6262. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6263. // Move
  6264. if (needToMove) {
  6265. this._updatePosition();
  6266. }
  6267. // Rotate
  6268. if (needToRotate) {
  6269. this.rotation.x += this.cameraRotation.x;
  6270. this.rotation.y += this.cameraRotation.y;
  6271. if (!this.noRotationConstraint) {
  6272. var limit = (Math.PI / 2) * 0.95;
  6273. if (this.rotation.x > limit)
  6274. this.rotation.x = limit;
  6275. if (this.rotation.x < -limit)
  6276. this.rotation.x = -limit;
  6277. }
  6278. }
  6279. // Inertia
  6280. if (needToMove) {
  6281. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6282. this.cameraDirection.x = 0;
  6283. }
  6284. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6285. this.cameraDirection.y = 0;
  6286. }
  6287. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6288. this.cameraDirection.z = 0;
  6289. }
  6290. this.cameraDirection.scaleInPlace(this.inertia);
  6291. }
  6292. if (needToRotate) {
  6293. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6294. this.cameraRotation.x = 0;
  6295. }
  6296. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6297. this.cameraRotation.y = 0;
  6298. }
  6299. this.cameraRotation.scaleInPlace(this.inertia);
  6300. }
  6301. };
  6302. TargetCamera.prototype._getViewMatrix = function () {
  6303. if (!this.lockedTarget) {
  6304. // Compute
  6305. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6306. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6307. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6308. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6309. this._lookAtTemp.invert();
  6310. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6311. } else {
  6312. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6313. }
  6314. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6315. // Computing target and final matrix
  6316. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6317. } else {
  6318. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6319. }
  6320. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6321. return this._viewMatrix;
  6322. };
  6323. return TargetCamera;
  6324. })(BABYLON.Camera);
  6325. BABYLON.TargetCamera = TargetCamera;
  6326. })(BABYLON || (BABYLON = {}));
  6327. //# sourceMappingURL=babylon.targetCamera.js.map
  6328. var BABYLON;
  6329. (function (BABYLON) {
  6330. var FollowCamera = (function (_super) {
  6331. __extends(FollowCamera, _super);
  6332. function FollowCamera(name, position, scene) {
  6333. _super.call(this, name, position, scene);
  6334. this.radius = 12;
  6335. this.rotationOffset = 0;
  6336. this.heightOffset = 4;
  6337. this.cameraAcceleration = 0.05;
  6338. this.maxCameraSpeed = 20;
  6339. }
  6340. FollowCamera.prototype.getRadians = function (degrees) {
  6341. return degrees * Math.PI / 180;
  6342. };
  6343. FollowCamera.prototype.follow = function (cameraTarget) {
  6344. if (!cameraTarget)
  6345. return;
  6346. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6347. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6348. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6349. var dx = targetX - this.position.x;
  6350. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6351. var dz = (targetZ) - this.position.z;
  6352. var vx = dx * this.cameraAcceleration * 2;
  6353. var vy = dy * this.cameraAcceleration;
  6354. var vz = dz * this.cameraAcceleration * 2;
  6355. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6356. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6357. }
  6358. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6359. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6360. }
  6361. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6362. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6363. }
  6364. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6365. this.setTarget(cameraTarget.position);
  6366. };
  6367. FollowCamera.prototype._update = function () {
  6368. _super.prototype._update.call(this);
  6369. this.follow(this.target);
  6370. };
  6371. return FollowCamera;
  6372. })(BABYLON.TargetCamera);
  6373. BABYLON.FollowCamera = FollowCamera;
  6374. })(BABYLON || (BABYLON = {}));
  6375. //# sourceMappingURL=babylon.followCamera.js.map
  6376. var BABYLON;
  6377. (function (BABYLON) {
  6378. var FreeCamera = (function (_super) {
  6379. __extends(FreeCamera, _super);
  6380. function FreeCamera(name, position, scene) {
  6381. _super.call(this, name, position, scene);
  6382. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6383. this.keysUp = [38];
  6384. this.keysDown = [40];
  6385. this.keysLeft = [37];
  6386. this.keysRight = [39];
  6387. this.checkCollisions = false;
  6388. this.applyGravity = false;
  6389. this.angularSensibility = 2000.0;
  6390. this._keys = [];
  6391. this._collider = new BABYLON.Collider();
  6392. this._needMoveForGravity = true;
  6393. this._oldPosition = BABYLON.Vector3.Zero();
  6394. this._diffPosition = BABYLON.Vector3.Zero();
  6395. this._newPosition = BABYLON.Vector3.Zero();
  6396. }
  6397. // Controls
  6398. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6399. var _this = this;
  6400. var previousPosition;
  6401. var engine = this.getEngine();
  6402. if (this._attachedElement) {
  6403. return;
  6404. }
  6405. this._attachedElement = element;
  6406. if (this._onMouseDown === undefined) {
  6407. this._onMouseDown = function (evt) {
  6408. previousPosition = {
  6409. x: evt.clientX,
  6410. y: evt.clientY
  6411. };
  6412. if (!noPreventDefault) {
  6413. evt.preventDefault();
  6414. }
  6415. };
  6416. this._onMouseUp = function (evt) {
  6417. previousPosition = null;
  6418. if (!noPreventDefault) {
  6419. evt.preventDefault();
  6420. }
  6421. };
  6422. this._onMouseOut = function (evt) {
  6423. previousPosition = null;
  6424. _this._keys = [];
  6425. if (!noPreventDefault) {
  6426. evt.preventDefault();
  6427. }
  6428. };
  6429. this._onMouseMove = function (evt) {
  6430. if (!previousPosition && !engine.isPointerLock) {
  6431. return;
  6432. }
  6433. var offsetX;
  6434. var offsetY;
  6435. if (!engine.isPointerLock) {
  6436. offsetX = evt.clientX - previousPosition.x;
  6437. offsetY = evt.clientY - previousPosition.y;
  6438. } else {
  6439. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6440. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6441. }
  6442. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6443. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6444. previousPosition = {
  6445. x: evt.clientX,
  6446. y: evt.clientY
  6447. };
  6448. if (!noPreventDefault) {
  6449. evt.preventDefault();
  6450. }
  6451. };
  6452. this._onKeyDown = function (evt) {
  6453. 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) {
  6454. var index = _this._keys.indexOf(evt.keyCode);
  6455. if (index === -1) {
  6456. _this._keys.push(evt.keyCode);
  6457. }
  6458. if (!noPreventDefault) {
  6459. evt.preventDefault();
  6460. }
  6461. }
  6462. };
  6463. this._onKeyUp = function (evt) {
  6464. 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) {
  6465. var index = _this._keys.indexOf(evt.keyCode);
  6466. if (index >= 0) {
  6467. _this._keys.splice(index, 1);
  6468. }
  6469. if (!noPreventDefault) {
  6470. evt.preventDefault();
  6471. }
  6472. }
  6473. };
  6474. this._onLostFocus = function () {
  6475. _this._keys = [];
  6476. };
  6477. this._reset = function () {
  6478. _this._keys = [];
  6479. previousPosition = null;
  6480. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6481. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6482. };
  6483. }
  6484. element.addEventListener("mousedown", this._onMouseDown, false);
  6485. element.addEventListener("mouseup", this._onMouseUp, false);
  6486. element.addEventListener("mouseout", this._onMouseOut, false);
  6487. element.addEventListener("mousemove", this._onMouseMove, false);
  6488. BABYLON.Tools.RegisterTopRootEvents([
  6489. { name: "keydown", handler: this._onKeyDown },
  6490. { name: "keyup", handler: this._onKeyUp },
  6491. { name: "blur", handler: this._onLostFocus }
  6492. ]);
  6493. };
  6494. FreeCamera.prototype.detachControl = function (element) {
  6495. if (this._attachedElement != element) {
  6496. return;
  6497. }
  6498. element.removeEventListener("mousedown", this._onMouseDown);
  6499. element.removeEventListener("mouseup", this._onMouseUp);
  6500. element.removeEventListener("mouseout", this._onMouseOut);
  6501. element.removeEventListener("mousemove", this._onMouseMove);
  6502. BABYLON.Tools.UnregisterTopRootEvents([
  6503. { name: "keydown", handler: this._onKeyDown },
  6504. { name: "keyup", handler: this._onKeyUp },
  6505. { name: "blur", handler: this._onLostFocus }
  6506. ]);
  6507. this._attachedElement = null;
  6508. if (this._reset) {
  6509. this._reset();
  6510. }
  6511. };
  6512. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6513. var globalPosition;
  6514. if (this.parent) {
  6515. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6516. } else {
  6517. globalPosition = this.position;
  6518. }
  6519. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6520. this._collider.radius = this.ellipsoid;
  6521. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6522. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6523. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6524. this.position.addInPlace(this._diffPosition);
  6525. if (this.onCollide) {
  6526. this.onCollide(this._collider.collidedMesh);
  6527. }
  6528. }
  6529. };
  6530. FreeCamera.prototype._checkInputs = function () {
  6531. if (!this._localDirection) {
  6532. this._localDirection = BABYLON.Vector3.Zero();
  6533. this._transformedDirection = BABYLON.Vector3.Zero();
  6534. }
  6535. for (var index = 0; index < this._keys.length; index++) {
  6536. var keyCode = this._keys[index];
  6537. var speed = this._computeLocalCameraSpeed();
  6538. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6539. this._localDirection.copyFromFloats(-speed, 0, 0);
  6540. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6541. this._localDirection.copyFromFloats(0, 0, speed);
  6542. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6543. this._localDirection.copyFromFloats(speed, 0, 0);
  6544. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6545. this._localDirection.copyFromFloats(0, 0, -speed);
  6546. }
  6547. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6548. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6549. this.cameraDirection.addInPlace(this._transformedDirection);
  6550. }
  6551. };
  6552. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6553. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6554. };
  6555. FreeCamera.prototype._updatePosition = function () {
  6556. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6557. this._collideWithWorld(this.cameraDirection);
  6558. if (this.applyGravity) {
  6559. var oldPosition = this.position;
  6560. this._collideWithWorld(this.getScene().gravity);
  6561. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6562. }
  6563. } else {
  6564. this.position.addInPlace(this.cameraDirection);
  6565. }
  6566. };
  6567. FreeCamera.prototype._update = function () {
  6568. this._checkInputs();
  6569. _super.prototype._update.call(this);
  6570. };
  6571. return FreeCamera;
  6572. })(BABYLON.TargetCamera);
  6573. BABYLON.FreeCamera = FreeCamera;
  6574. })(BABYLON || (BABYLON = {}));
  6575. //# sourceMappingURL=babylon.freeCamera.js.map
  6576. var BABYLON;
  6577. (function (BABYLON) {
  6578. // We're mainly based on the logic defined into the FreeCamera code
  6579. var TouchCamera = (function (_super) {
  6580. __extends(TouchCamera, _super);
  6581. function TouchCamera(name, position, scene) {
  6582. _super.call(this, name, position, scene);
  6583. this._offsetX = null;
  6584. this._offsetY = null;
  6585. this._pointerCount = 0;
  6586. this._pointerPressed = [];
  6587. this.angularSensibility = 200000.0;
  6588. this.moveSensibility = 500.0;
  6589. }
  6590. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6591. var _this = this;
  6592. var previousPosition;
  6593. if (this._attachedCanvas) {
  6594. return;
  6595. }
  6596. this._attachedCanvas = canvas;
  6597. if (this._onPointerDown === undefined) {
  6598. this._onPointerDown = function (evt) {
  6599. if (!noPreventDefault) {
  6600. evt.preventDefault();
  6601. }
  6602. _this._pointerPressed.push(evt.pointerId);
  6603. if (_this._pointerPressed.length !== 1) {
  6604. return;
  6605. }
  6606. previousPosition = {
  6607. x: evt.clientX,
  6608. y: evt.clientY
  6609. };
  6610. };
  6611. this._onPointerUp = function (evt) {
  6612. if (!noPreventDefault) {
  6613. evt.preventDefault();
  6614. }
  6615. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6616. if (index === -1) {
  6617. return;
  6618. }
  6619. _this._pointerPressed.splice(index, 1);
  6620. if (index != 0) {
  6621. return;
  6622. }
  6623. previousPosition = null;
  6624. _this._offsetX = null;
  6625. _this._offsetY = null;
  6626. };
  6627. this._onPointerMove = function (evt) {
  6628. if (!noPreventDefault) {
  6629. evt.preventDefault();
  6630. }
  6631. if (!previousPosition) {
  6632. return;
  6633. }
  6634. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6635. if (index != 0) {
  6636. return;
  6637. }
  6638. _this._offsetX = evt.clientX - previousPosition.x;
  6639. _this._offsetY = -(evt.clientY - previousPosition.y);
  6640. };
  6641. this._onLostFocus = function () {
  6642. _this._offsetX = null;
  6643. _this._offsetY = null;
  6644. };
  6645. }
  6646. canvas.addEventListener("pointerdown", this._onPointerDown);
  6647. canvas.addEventListener("pointerup", this._onPointerUp);
  6648. canvas.addEventListener("pointerout", this._onPointerUp);
  6649. canvas.addEventListener("pointermove", this._onPointerMove);
  6650. BABYLON.Tools.RegisterTopRootEvents([
  6651. { name: "blur", handler: this._onLostFocus }
  6652. ]);
  6653. };
  6654. TouchCamera.prototype.detachControl = function (canvas) {
  6655. if (this._attachedCanvas != canvas) {
  6656. return;
  6657. }
  6658. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6659. canvas.removeEventListener("pointerup", this._onPointerUp);
  6660. canvas.removeEventListener("pointerout", this._onPointerUp);
  6661. canvas.removeEventListener("pointermove", this._onPointerMove);
  6662. BABYLON.Tools.UnregisterTopRootEvents([
  6663. { name: "blur", handler: this._onLostFocus }
  6664. ]);
  6665. this._attachedCanvas = null;
  6666. };
  6667. TouchCamera.prototype._checkInputs = function () {
  6668. if (!this._offsetX) {
  6669. return;
  6670. }
  6671. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6672. if (this._pointerPressed.length > 1) {
  6673. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6674. } else {
  6675. var speed = this._computeLocalCameraSpeed();
  6676. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6677. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6678. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6679. }
  6680. };
  6681. return TouchCamera;
  6682. })(BABYLON.FreeCamera);
  6683. BABYLON.TouchCamera = TouchCamera;
  6684. })(BABYLON || (BABYLON = {}));
  6685. //# sourceMappingURL=babylon.touchCamera.js.map
  6686. var BABYLON;
  6687. (function (BABYLON) {
  6688. // We're mainly based on the logic defined into the FreeCamera code
  6689. var DeviceOrientationCamera = (function (_super) {
  6690. __extends(DeviceOrientationCamera, _super);
  6691. function DeviceOrientationCamera(name, position, scene) {
  6692. var _this = this;
  6693. _super.call(this, name, position, scene);
  6694. this._offsetX = null;
  6695. this._offsetY = null;
  6696. this._orientationGamma = 0;
  6697. this._orientationBeta = 0;
  6698. this._initialOrientationGamma = 0;
  6699. this._initialOrientationBeta = 0;
  6700. this.angularSensibility = 10000.0;
  6701. this.moveSensibility = 50.0;
  6702. window.addEventListener("resize", function () {
  6703. _this._initialOrientationGamma = null;
  6704. }, false);
  6705. }
  6706. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6707. var _this = this;
  6708. if (this._attachedCanvas) {
  6709. return;
  6710. }
  6711. this._attachedCanvas = canvas;
  6712. if (!this._orientationChanged) {
  6713. this._orientationChanged = function (evt) {
  6714. if (!_this._initialOrientationGamma) {
  6715. _this._initialOrientationGamma = evt.gamma;
  6716. _this._initialOrientationBeta = evt.beta;
  6717. }
  6718. _this._orientationGamma = evt.gamma;
  6719. _this._orientationBeta = evt.beta;
  6720. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6721. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6722. };
  6723. }
  6724. window.addEventListener("deviceorientation", this._orientationChanged);
  6725. };
  6726. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6727. if (this._attachedCanvas != canvas) {
  6728. return;
  6729. }
  6730. window.removeEventListener("deviceorientation", this._orientationChanged);
  6731. this._attachedCanvas = null;
  6732. this._orientationGamma = 0;
  6733. this._orientationBeta = 0;
  6734. this._initialOrientationGamma = 0;
  6735. this._initialOrientationBeta = 0;
  6736. };
  6737. DeviceOrientationCamera.prototype._checkInputs = function () {
  6738. if (!this._offsetX) {
  6739. return;
  6740. }
  6741. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6742. var speed = this._computeLocalCameraSpeed();
  6743. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6744. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6745. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6746. };
  6747. return DeviceOrientationCamera;
  6748. })(BABYLON.FreeCamera);
  6749. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6750. })(BABYLON || (BABYLON = {}));
  6751. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6752. var BABYLON;
  6753. (function (BABYLON) {
  6754. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6755. var ArcRotateCamera = (function (_super) {
  6756. __extends(ArcRotateCamera, _super);
  6757. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6758. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6759. this.alpha = alpha;
  6760. this.beta = beta;
  6761. this.radius = radius;
  6762. this.target = target;
  6763. this.inertialAlphaOffset = 0;
  6764. this.inertialBetaOffset = 0;
  6765. this.inertialRadiusOffset = 0;
  6766. this.lowerAlphaLimit = null;
  6767. this.upperAlphaLimit = null;
  6768. this.lowerBetaLimit = 0.01;
  6769. this.upperBetaLimit = Math.PI;
  6770. this.lowerRadiusLimit = null;
  6771. this.upperRadiusLimit = null;
  6772. this.angularSensibility = 1000.0;
  6773. this.wheelPrecision = 3.0;
  6774. this.keysUp = [38];
  6775. this.keysDown = [40];
  6776. this.keysLeft = [37];
  6777. this.keysRight = [39];
  6778. this.zoomOnFactor = 1;
  6779. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6780. this._keys = [];
  6781. this._viewMatrix = new BABYLON.Matrix();
  6782. this.checkCollisions = false;
  6783. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6784. this._collider = new BABYLON.Collider();
  6785. this._previousPosition = BABYLON.Vector3.Zero();
  6786. this._collisionVelocity = BABYLON.Vector3.Zero();
  6787. this._newPosition = BABYLON.Vector3.Zero();
  6788. // Pinch
  6789. // value for pinch step scaling
  6790. // set to 20 by default
  6791. this.pinchPrecision = 20;
  6792. this.getViewMatrix();
  6793. }
  6794. ArcRotateCamera.prototype._getTargetPosition = function () {
  6795. return this.target.position || this.target;
  6796. };
  6797. // Cache
  6798. ArcRotateCamera.prototype._initCache = function () {
  6799. _super.prototype._initCache.call(this);
  6800. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6801. this._cache.alpha = undefined;
  6802. this._cache.beta = undefined;
  6803. this._cache.radius = undefined;
  6804. this._cache.targetScreenOffset = undefined;
  6805. };
  6806. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6807. if (!ignoreParentClass) {
  6808. _super.prototype._updateCache.call(this);
  6809. }
  6810. this._cache.target.copyFrom(this._getTargetPosition());
  6811. this._cache.alpha = this.alpha;
  6812. this._cache.beta = this.beta;
  6813. this._cache.radius = this.radius;
  6814. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6815. };
  6816. // Synchronized
  6817. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6818. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6819. return false;
  6820. 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);
  6821. };
  6822. // Methods
  6823. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6824. var _this = this;
  6825. var previousPosition;
  6826. var pointerId;
  6827. // to know if pinch started
  6828. var pinchStarted = false;
  6829. // two pinch point on X
  6830. // that will use for find if user action is pinch open or pinch close
  6831. var pinchPointX1, pinchPointX2;
  6832. if (this._attachedElement) {
  6833. return;
  6834. }
  6835. this._attachedElement = element;
  6836. var engine = this.getEngine();
  6837. if (this._onPointerDown === undefined) {
  6838. this._onPointerDown = function (evt) {
  6839. if (pointerId) {
  6840. return;
  6841. }
  6842. pointerId = evt.pointerId;
  6843. previousPosition = {
  6844. x: evt.clientX,
  6845. y: evt.clientY
  6846. };
  6847. if (!noPreventDefault) {
  6848. evt.preventDefault();
  6849. }
  6850. };
  6851. this._onPointerUp = function (evt) {
  6852. previousPosition = null;
  6853. pointerId = null;
  6854. if (!noPreventDefault) {
  6855. evt.preventDefault();
  6856. }
  6857. };
  6858. this._onPointerMove = function (evt) {
  6859. if (!previousPosition) {
  6860. return;
  6861. }
  6862. if (pointerId !== evt.pointerId) {
  6863. return;
  6864. }
  6865. // return pinch is started
  6866. if (pinchStarted) {
  6867. return;
  6868. }
  6869. var offsetX = evt.clientX - previousPosition.x;
  6870. var offsetY = evt.clientY - previousPosition.y;
  6871. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6872. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6873. previousPosition = {
  6874. x: evt.clientX,
  6875. y: evt.clientY
  6876. };
  6877. if (!noPreventDefault) {
  6878. evt.preventDefault();
  6879. }
  6880. };
  6881. this._onMouseMove = function (evt) {
  6882. if (!engine.isPointerLock) {
  6883. return;
  6884. }
  6885. // return pinch is started
  6886. if (pinchStarted) {
  6887. return;
  6888. }
  6889. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6890. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6891. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6892. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6893. if (!noPreventDefault) {
  6894. evt.preventDefault();
  6895. }
  6896. };
  6897. this._wheel = function (event) {
  6898. var delta = 0;
  6899. if (event.wheelDelta) {
  6900. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6901. } else if (event.detail) {
  6902. delta = -event.detail / _this.wheelPrecision;
  6903. }
  6904. if (delta)
  6905. _this.inertialRadiusOffset += delta;
  6906. if (event.preventDefault) {
  6907. if (!noPreventDefault) {
  6908. event.preventDefault();
  6909. }
  6910. }
  6911. };
  6912. this._onKeyDown = function (evt) {
  6913. 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) {
  6914. var index = _this._keys.indexOf(evt.keyCode);
  6915. if (index === -1) {
  6916. _this._keys.push(evt.keyCode);
  6917. }
  6918. if (evt.preventDefault) {
  6919. if (!noPreventDefault) {
  6920. evt.preventDefault();
  6921. }
  6922. }
  6923. }
  6924. };
  6925. this._onKeyUp = function (evt) {
  6926. 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) {
  6927. var index = _this._keys.indexOf(evt.keyCode);
  6928. if (index >= 0) {
  6929. _this._keys.splice(index, 1);
  6930. }
  6931. if (evt.preventDefault) {
  6932. if (!noPreventDefault) {
  6933. evt.preventDefault();
  6934. }
  6935. }
  6936. }
  6937. };
  6938. this._onLostFocus = function () {
  6939. _this._keys = [];
  6940. pointerId = null;
  6941. };
  6942. this._onGestureStart = function (e) {
  6943. if (window.MSGesture === undefined) {
  6944. return;
  6945. }
  6946. if (!_this._MSGestureHandler) {
  6947. _this._MSGestureHandler = new MSGesture();
  6948. _this._MSGestureHandler.target = element;
  6949. }
  6950. _this._MSGestureHandler.addPointer(e.pointerId);
  6951. };
  6952. this._onGesture = function (e) {
  6953. _this.radius *= e.scale;
  6954. if (e.preventDefault) {
  6955. if (!noPreventDefault) {
  6956. e.stopPropagation();
  6957. e.preventDefault();
  6958. }
  6959. }
  6960. };
  6961. this._reset = function () {
  6962. _this._keys = [];
  6963. _this.inertialAlphaOffset = 0;
  6964. _this.inertialBetaOffset = 0;
  6965. _this.inertialRadiusOffset = 0;
  6966. previousPosition = null;
  6967. pointerId = null;
  6968. };
  6969. this._touchStart = function (event) {
  6970. if (event.touches.length === 2) {
  6971. //-- start pinch if two fingers on the screen
  6972. pinchStarted = true;
  6973. _this._pinchStart(event);
  6974. }
  6975. };
  6976. this._touchMove = function (event) {
  6977. if (pinchStarted) {
  6978. //-- make scaling
  6979. _this._pinchMove(event);
  6980. }
  6981. };
  6982. this._touchEnd = function (event) {
  6983. if (pinchStarted) {
  6984. //-- end of pinch
  6985. _this._pinchEnd(event);
  6986. }
  6987. };
  6988. this._pinchStart = function (event) {
  6989. // save origin touch point
  6990. pinchPointX1 = event.touches[0].clientX;
  6991. pinchPointX2 = event.touches[1].clientX;
  6992. // block the camera
  6993. // if not it rotate around target during pinch
  6994. pinchStarted = true;
  6995. };
  6996. this._pinchMove = function (event) {
  6997. // variable for new camera's radius
  6998. var delta = 0;
  6999. // variables to know if pinch open or pinch close
  7000. var direction = 1;
  7001. var distanceXOrigine, distanceXNow;
  7002. if (event.touches.length !== 2)
  7003. return;
  7004. // calculate absolute distances of the two fingers
  7005. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7006. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7007. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7008. if (distanceXNow < distanceXOrigine) {
  7009. direction = -1;
  7010. }
  7011. // calculate new radius
  7012. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7013. // set new radius
  7014. _this.inertialRadiusOffset -= delta;
  7015. // save origin touch point
  7016. pinchPointX1 = event.touches[0].clientX;
  7017. pinchPointX2 = event.touches[1].clientX;
  7018. };
  7019. this._pinchEnd = function (event) {
  7020. // cancel pinch and deblock camera rotation
  7021. pinchStarted = false;
  7022. };
  7023. }
  7024. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7025. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7026. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7027. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7028. element.addEventListener("mousemove", this._onMouseMove, false);
  7029. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7030. element.addEventListener("MSGestureChange", this._onGesture, false);
  7031. element.addEventListener('mousewheel', this._wheel, false);
  7032. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7033. // pinch
  7034. element.addEventListener('touchstart', this._touchStart, false);
  7035. element.addEventListener('touchmove', this._touchMove, false);
  7036. element.addEventListener('touchend', this._touchEnd, false);
  7037. BABYLON.Tools.RegisterTopRootEvents([
  7038. { name: "keydown", handler: this._onKeyDown },
  7039. { name: "keyup", handler: this._onKeyUp },
  7040. { name: "blur", handler: this._onLostFocus }
  7041. ]);
  7042. };
  7043. ArcRotateCamera.prototype.detachControl = function (element) {
  7044. if (this._attachedElement != element) {
  7045. return;
  7046. }
  7047. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7048. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7049. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7050. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7051. element.removeEventListener("mousemove", this._onMouseMove);
  7052. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7053. element.removeEventListener("MSGestureChange", this._onGesture);
  7054. element.removeEventListener('mousewheel', this._wheel);
  7055. element.removeEventListener('DOMMouseScroll', this._wheel);
  7056. // pinch
  7057. element.removeEventListener('touchstart', this._touchStart);
  7058. element.removeEventListener('touchmove', this._touchMove);
  7059. element.removeEventListener('touchend', this._touchEnd);
  7060. BABYLON.Tools.UnregisterTopRootEvents([
  7061. { name: "keydown", handler: this._onKeyDown },
  7062. { name: "keyup", handler: this._onKeyUp },
  7063. { name: "blur", handler: this._onLostFocus }
  7064. ]);
  7065. this._MSGestureHandler = null;
  7066. this._attachedElement = null;
  7067. if (this._reset) {
  7068. this._reset();
  7069. }
  7070. };
  7071. ArcRotateCamera.prototype._update = function () {
  7072. for (var index = 0; index < this._keys.length; index++) {
  7073. var keyCode = this._keys[index];
  7074. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7075. this.inertialAlphaOffset -= 0.01;
  7076. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  7077. this.inertialBetaOffset -= 0.01;
  7078. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  7079. this.inertialAlphaOffset += 0.01;
  7080. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  7081. this.inertialBetaOffset += 0.01;
  7082. }
  7083. }
  7084. // Inertia
  7085. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7086. this.alpha += this.inertialAlphaOffset;
  7087. this.beta += this.inertialBetaOffset;
  7088. this.radius -= this.inertialRadiusOffset;
  7089. this.inertialAlphaOffset *= this.inertia;
  7090. this.inertialBetaOffset *= this.inertia;
  7091. this.inertialRadiusOffset *= this.inertia;
  7092. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7093. this.inertialAlphaOffset = 0;
  7094. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7095. this.inertialBetaOffset = 0;
  7096. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7097. this.inertialRadiusOffset = 0;
  7098. }
  7099. // Limits
  7100. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7101. this.alpha = this.lowerAlphaLimit;
  7102. }
  7103. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7104. this.alpha = this.upperAlphaLimit;
  7105. }
  7106. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7107. this.beta = this.lowerBetaLimit;
  7108. }
  7109. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7110. this.beta = this.upperBetaLimit;
  7111. }
  7112. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7113. this.radius = this.lowerRadiusLimit;
  7114. }
  7115. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7116. this.radius = this.upperRadiusLimit;
  7117. }
  7118. };
  7119. ArcRotateCamera.prototype.setPosition = function (position) {
  7120. var radiusv3 = position.subtract(this._getTargetPosition());
  7121. this.radius = radiusv3.length();
  7122. // Alpha
  7123. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7124. if (radiusv3.z < 0) {
  7125. this.alpha = 2 * Math.PI - this.alpha;
  7126. }
  7127. // Beta
  7128. this.beta = Math.acos(radiusv3.y / this.radius);
  7129. };
  7130. ArcRotateCamera.prototype._getViewMatrix = function () {
  7131. // Compute
  7132. var cosa = Math.cos(this.alpha);
  7133. var sina = Math.sin(this.alpha);
  7134. var cosb = Math.cos(this.beta);
  7135. var sinb = Math.sin(this.beta);
  7136. var target = this._getTargetPosition();
  7137. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7138. if (this.checkCollisions) {
  7139. this._collider.radius = this.collisionRadius;
  7140. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7141. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7142. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7143. this.position.copyFrom(this._previousPosition);
  7144. this.alpha = this._previousAlpha;
  7145. this.beta = this._previousBeta;
  7146. this.radius = this._previousRadius;
  7147. if (this.onCollide) {
  7148. this.onCollide(this._collider.collidedMesh);
  7149. }
  7150. }
  7151. }
  7152. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7153. this._previousAlpha = this.alpha;
  7154. this._previousBeta = this.beta;
  7155. this._previousRadius = this.radius;
  7156. this._previousPosition.copyFrom(this.position);
  7157. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7158. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7159. return this._viewMatrix;
  7160. };
  7161. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7162. meshes = meshes || this.getScene().meshes;
  7163. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7164. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7165. this.radius = distance * this.zoomOnFactor;
  7166. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7167. };
  7168. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7169. var meshesOrMinMaxVector;
  7170. var distance;
  7171. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7172. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7173. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7174. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7175. } else {
  7176. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7177. distance = meshesOrMinMaxVectorAndDistance.distance;
  7178. }
  7179. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7180. this.maxZ = distance * 2;
  7181. };
  7182. return ArcRotateCamera;
  7183. })(BABYLON.Camera);
  7184. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7185. })(BABYLON || (BABYLON = {}));
  7186. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  7187. var BABYLON;
  7188. (function (BABYLON) {
  7189. var Scene = (function () {
  7190. // Constructor
  7191. function Scene(engine) {
  7192. // Members
  7193. this.autoClear = true;
  7194. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7195. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7196. this.forceWireframe = false;
  7197. this.forcePointsCloud = false;
  7198. this.forceShowBoundingBoxes = false;
  7199. this.animationsEnabled = true;
  7200. this.cameraToUseForPointers = null;
  7201. // Fog
  7202. this.fogEnabled = true;
  7203. this.fogMode = Scene.FOGMODE_NONE;
  7204. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7205. this.fogDensity = 0.1;
  7206. this.fogStart = 0;
  7207. this.fogEnd = 1000.0;
  7208. // Lights
  7209. this.shadowsEnabled = true;
  7210. this.lightsEnabled = true;
  7211. this.lights = new Array();
  7212. // Cameras
  7213. this.cameras = new Array();
  7214. this.activeCameras = new Array();
  7215. // Meshes
  7216. this.meshes = new Array();
  7217. // Geometries
  7218. this._geometries = new Array();
  7219. this.materials = new Array();
  7220. this.multiMaterials = new Array();
  7221. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7222. // Textures
  7223. this.texturesEnabled = true;
  7224. this.textures = new Array();
  7225. // Particles
  7226. this.particlesEnabled = true;
  7227. this.particleSystems = new Array();
  7228. // Sprites
  7229. this.spriteManagers = new Array();
  7230. // Layers
  7231. this.layers = new Array();
  7232. // Skeletons
  7233. this.skeletonsEnabled = true;
  7234. this.skeletons = new Array();
  7235. // Lens flares
  7236. this.lensFlaresEnabled = true;
  7237. this.lensFlareSystems = new Array();
  7238. // Collisions
  7239. this.collisionsEnabled = true;
  7240. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7241. // Postprocesses
  7242. this.postProcessesEnabled = true;
  7243. // Customs render targets
  7244. this.renderTargetsEnabled = true;
  7245. this.customRenderTargets = new Array();
  7246. // Imported meshes
  7247. this.importedMeshesFiles = new Array();
  7248. this._actionManagers = new Array();
  7249. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7250. // Procedural textures
  7251. this.proceduralTexturesEnabled = true;
  7252. this._proceduralTextures = new Array();
  7253. this.soundTracks = new Array();
  7254. this._totalVertices = 0;
  7255. this._activeVertices = 0;
  7256. this._activeParticles = 0;
  7257. this._lastFrameDuration = 0;
  7258. this._evaluateActiveMeshesDuration = 0;
  7259. this._renderTargetsDuration = 0;
  7260. this._particlesDuration = 0;
  7261. this._renderDuration = 0;
  7262. this._spritesDuration = 0;
  7263. this._animationRatio = 0;
  7264. this._renderId = 0;
  7265. this._executeWhenReadyTimeoutId = -1;
  7266. this._toBeDisposed = new BABYLON.SmartArray(256);
  7267. this._onReadyCallbacks = new Array();
  7268. this._pendingData = [];
  7269. this._onBeforeRenderCallbacks = new Array();
  7270. this._onAfterRenderCallbacks = new Array();
  7271. this._activeMeshes = new BABYLON.SmartArray(256);
  7272. this._processedMaterials = new BABYLON.SmartArray(256);
  7273. this._renderTargets = new BABYLON.SmartArray(256);
  7274. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7275. this._activeSkeletons = new BABYLON.SmartArray(32);
  7276. this._activeBones = 0;
  7277. this._activeAnimatables = new Array();
  7278. this._transformMatrix = BABYLON.Matrix.Zero();
  7279. this._scaledPosition = BABYLON.Vector3.Zero();
  7280. this._scaledVelocity = BABYLON.Vector3.Zero();
  7281. this._engine = engine;
  7282. engine.scenes.push(this);
  7283. this._renderingManager = new BABYLON.RenderingManager(this);
  7284. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7285. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7286. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7287. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7288. this.attachControl();
  7289. this._debugLayer = new BABYLON.DebugLayer(this);
  7290. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7291. }
  7292. Object.defineProperty(Scene.prototype, "debugLayer", {
  7293. // Properties
  7294. get: function () {
  7295. return this._debugLayer;
  7296. },
  7297. enumerable: true,
  7298. configurable: true
  7299. });
  7300. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7301. get: function () {
  7302. return this._meshUnderPointer;
  7303. },
  7304. enumerable: true,
  7305. configurable: true
  7306. });
  7307. Object.defineProperty(Scene.prototype, "pointerX", {
  7308. get: function () {
  7309. return this._pointerX;
  7310. },
  7311. enumerable: true,
  7312. configurable: true
  7313. });
  7314. Object.defineProperty(Scene.prototype, "pointerY", {
  7315. get: function () {
  7316. return this._pointerY;
  7317. },
  7318. enumerable: true,
  7319. configurable: true
  7320. });
  7321. Scene.prototype.getCachedMaterial = function () {
  7322. return this._cachedMaterial;
  7323. };
  7324. Scene.prototype.getBoundingBoxRenderer = function () {
  7325. return this._boundingBoxRenderer;
  7326. };
  7327. Scene.prototype.getOutlineRenderer = function () {
  7328. return this._outlineRenderer;
  7329. };
  7330. Scene.prototype.getEngine = function () {
  7331. return this._engine;
  7332. };
  7333. Scene.prototype.getTotalVertices = function () {
  7334. return this._totalVertices;
  7335. };
  7336. Scene.prototype.getActiveVertices = function () {
  7337. return this._activeVertices;
  7338. };
  7339. Scene.prototype.getActiveParticles = function () {
  7340. return this._activeParticles;
  7341. };
  7342. Scene.prototype.getActiveBones = function () {
  7343. return this._activeBones;
  7344. };
  7345. // Stats
  7346. Scene.prototype.getLastFrameDuration = function () {
  7347. return this._lastFrameDuration;
  7348. };
  7349. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7350. return this._evaluateActiveMeshesDuration;
  7351. };
  7352. Scene.prototype.getActiveMeshes = function () {
  7353. return this._activeMeshes;
  7354. };
  7355. Scene.prototype.getRenderTargetsDuration = function () {
  7356. return this._renderTargetsDuration;
  7357. };
  7358. Scene.prototype.getRenderDuration = function () {
  7359. return this._renderDuration;
  7360. };
  7361. Scene.prototype.getParticlesDuration = function () {
  7362. return this._particlesDuration;
  7363. };
  7364. Scene.prototype.getSpritesDuration = function () {
  7365. return this._spritesDuration;
  7366. };
  7367. Scene.prototype.getAnimationRatio = function () {
  7368. return this._animationRatio;
  7369. };
  7370. Scene.prototype.getRenderId = function () {
  7371. return this._renderId;
  7372. };
  7373. Scene.prototype._updatePointerPosition = function (evt) {
  7374. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7375. this._pointerX = evt.clientX - canvasRect.left;
  7376. this._pointerY = evt.clientY - canvasRect.top;
  7377. if (this.cameraToUseForPointers) {
  7378. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7379. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7380. }
  7381. };
  7382. // Pointers handling
  7383. Scene.prototype.attachControl = function () {
  7384. var _this = this;
  7385. this._onPointerMove = function (evt) {
  7386. var canvas = _this._engine.getRenderingCanvas();
  7387. _this._updatePointerPosition(evt);
  7388. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  7389. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  7390. }, false, _this.cameraToUseForPointers);
  7391. if (pickResult.hit) {
  7392. _this._meshUnderPointer = pickResult.pickedMesh;
  7393. _this.setPointerOverMesh(pickResult.pickedMesh);
  7394. canvas.style.cursor = "pointer";
  7395. } else {
  7396. _this.setPointerOverMesh(null);
  7397. canvas.style.cursor = "";
  7398. _this._meshUnderPointer = null;
  7399. }
  7400. };
  7401. this._onPointerDown = function (evt) {
  7402. var predicate = null;
  7403. if (!_this.onPointerDown) {
  7404. predicate = function (mesh) {
  7405. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7406. };
  7407. }
  7408. _this._updatePointerPosition(evt);
  7409. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7410. if (pickResult.hit) {
  7411. if (pickResult.pickedMesh.actionManager) {
  7412. switch (evt.button) {
  7413. case 0:
  7414. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7415. break;
  7416. case 1:
  7417. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7418. break;
  7419. case 2:
  7420. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7421. break;
  7422. }
  7423. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7424. }
  7425. }
  7426. if (_this.onPointerDown) {
  7427. _this.onPointerDown(evt, pickResult);
  7428. }
  7429. };
  7430. this._onKeyDown = function (evt) {
  7431. if (_this.actionManager) {
  7432. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7433. }
  7434. };
  7435. this._onKeyUp = function (evt) {
  7436. if (_this.actionManager) {
  7437. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7438. }
  7439. };
  7440. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7441. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7442. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7443. window.addEventListener("keydown", this._onKeyDown, false);
  7444. window.addEventListener("keyup", this._onKeyUp, false);
  7445. };
  7446. Scene.prototype.detachControl = function () {
  7447. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7448. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7449. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7450. window.removeEventListener("keydown", this._onKeyDown);
  7451. window.removeEventListener("keyup", this._onKeyUp);
  7452. };
  7453. // Ready
  7454. Scene.prototype.isReady = function () {
  7455. if (this._pendingData.length > 0) {
  7456. return false;
  7457. }
  7458. for (var index = 0; index < this._geometries.length; index++) {
  7459. var geometry = this._geometries[index];
  7460. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7461. return false;
  7462. }
  7463. }
  7464. for (index = 0; index < this.meshes.length; index++) {
  7465. var mesh = this.meshes[index];
  7466. if (!mesh.isReady()) {
  7467. return false;
  7468. }
  7469. var mat = mesh.material;
  7470. if (mat) {
  7471. if (!mat.isReady(mesh)) {
  7472. return false;
  7473. }
  7474. }
  7475. }
  7476. return true;
  7477. };
  7478. Scene.prototype.resetCachedMaterial = function () {
  7479. this._cachedMaterial = null;
  7480. };
  7481. Scene.prototype.registerBeforeRender = function (func) {
  7482. this._onBeforeRenderCallbacks.push(func);
  7483. };
  7484. Scene.prototype.unregisterBeforeRender = function (func) {
  7485. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7486. if (index > -1) {
  7487. this._onBeforeRenderCallbacks.splice(index, 1);
  7488. }
  7489. };
  7490. Scene.prototype.registerAfterRender = function (func) {
  7491. this._onAfterRenderCallbacks.push(func);
  7492. };
  7493. Scene.prototype.unregisterAfterRender = function (func) {
  7494. var index = this._onAfterRenderCallbacks.indexOf(func);
  7495. if (index > -1) {
  7496. this._onAfterRenderCallbacks.splice(index, 1);
  7497. }
  7498. };
  7499. Scene.prototype._addPendingData = function (data) {
  7500. this._pendingData.push(data);
  7501. };
  7502. Scene.prototype._removePendingData = function (data) {
  7503. var index = this._pendingData.indexOf(data);
  7504. if (index !== -1) {
  7505. this._pendingData.splice(index, 1);
  7506. }
  7507. };
  7508. Scene.prototype.getWaitingItemsCount = function () {
  7509. return this._pendingData.length;
  7510. };
  7511. Scene.prototype.executeWhenReady = function (func) {
  7512. var _this = this;
  7513. this._onReadyCallbacks.push(func);
  7514. if (this._executeWhenReadyTimeoutId !== -1) {
  7515. return;
  7516. }
  7517. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7518. _this._checkIsReady();
  7519. }, 150);
  7520. };
  7521. Scene.prototype._checkIsReady = function () {
  7522. var _this = this;
  7523. if (this.isReady()) {
  7524. this._onReadyCallbacks.forEach(function (func) {
  7525. func();
  7526. });
  7527. this._onReadyCallbacks = [];
  7528. this._executeWhenReadyTimeoutId = -1;
  7529. return;
  7530. }
  7531. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7532. _this._checkIsReady();
  7533. }, 150);
  7534. };
  7535. // Animations
  7536. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7537. if (speedRatio === undefined) {
  7538. speedRatio = 1.0;
  7539. }
  7540. this.stopAnimation(target);
  7541. if (!animatable) {
  7542. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7543. }
  7544. // Local animations
  7545. if (target.animations) {
  7546. animatable.appendAnimations(target, target.animations);
  7547. }
  7548. // Children animations
  7549. if (target.getAnimatables) {
  7550. var animatables = target.getAnimatables();
  7551. for (var index = 0; index < animatables.length; index++) {
  7552. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7553. }
  7554. }
  7555. return animatable;
  7556. };
  7557. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7558. if (speedRatio === undefined) {
  7559. speedRatio = 1.0;
  7560. }
  7561. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7562. return animatable;
  7563. };
  7564. Scene.prototype.getAnimatableByTarget = function (target) {
  7565. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7566. if (this._activeAnimatables[index].target === target) {
  7567. return this._activeAnimatables[index];
  7568. }
  7569. }
  7570. return null;
  7571. };
  7572. Scene.prototype.stopAnimation = function (target) {
  7573. var animatable = this.getAnimatableByTarget(target);
  7574. if (animatable) {
  7575. animatable.stop();
  7576. }
  7577. };
  7578. Scene.prototype._animate = function () {
  7579. if (!this.animationsEnabled) {
  7580. return;
  7581. }
  7582. if (!this._animationStartDate) {
  7583. this._animationStartDate = BABYLON.Tools.Now;
  7584. }
  7585. // Getting time
  7586. var now = BABYLON.Tools.Now;
  7587. var delay = now - this._animationStartDate;
  7588. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7589. if (!this._activeAnimatables[index]._animate(delay)) {
  7590. this._activeAnimatables.splice(index, 1);
  7591. index--;
  7592. }
  7593. }
  7594. };
  7595. // Matrix
  7596. Scene.prototype.getViewMatrix = function () {
  7597. return this._viewMatrix;
  7598. };
  7599. Scene.prototype.getProjectionMatrix = function () {
  7600. return this._projectionMatrix;
  7601. };
  7602. Scene.prototype.getTransformMatrix = function () {
  7603. return this._transformMatrix;
  7604. };
  7605. Scene.prototype.setTransformMatrix = function (view, projection) {
  7606. this._viewMatrix = view;
  7607. this._projectionMatrix = projection;
  7608. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7609. };
  7610. // Methods
  7611. Scene.prototype.setActiveCameraByID = function (id) {
  7612. var camera = this.getCameraByID(id);
  7613. if (camera) {
  7614. this.activeCamera = camera;
  7615. return camera;
  7616. }
  7617. return null;
  7618. };
  7619. Scene.prototype.setActiveCameraByName = function (name) {
  7620. var camera = this.getCameraByName(name);
  7621. if (camera) {
  7622. this.activeCamera = camera;
  7623. return camera;
  7624. }
  7625. return null;
  7626. };
  7627. Scene.prototype.getMaterialByID = function (id) {
  7628. for (var index = 0; index < this.materials.length; index++) {
  7629. if (this.materials[index].id === id) {
  7630. return this.materials[index];
  7631. }
  7632. }
  7633. return null;
  7634. };
  7635. Scene.prototype.getMaterialByName = function (name) {
  7636. for (var index = 0; index < this.materials.length; index++) {
  7637. if (this.materials[index].name === name) {
  7638. return this.materials[index];
  7639. }
  7640. }
  7641. return null;
  7642. };
  7643. Scene.prototype.getCameraByID = function (id) {
  7644. for (var index = 0; index < this.cameras.length; index++) {
  7645. if (this.cameras[index].id === id) {
  7646. return this.cameras[index];
  7647. }
  7648. }
  7649. return null;
  7650. };
  7651. Scene.prototype.getCameraByName = function (name) {
  7652. for (var index = 0; index < this.cameras.length; index++) {
  7653. if (this.cameras[index].name === name) {
  7654. return this.cameras[index];
  7655. }
  7656. }
  7657. return null;
  7658. };
  7659. Scene.prototype.getLightByName = function (name) {
  7660. for (var index = 0; index < this.lights.length; index++) {
  7661. if (this.lights[index].name === name) {
  7662. return this.lights[index];
  7663. }
  7664. }
  7665. return null;
  7666. };
  7667. Scene.prototype.getLightByID = function (id) {
  7668. for (var index = 0; index < this.lights.length; index++) {
  7669. if (this.lights[index].id === id) {
  7670. return this.lights[index];
  7671. }
  7672. }
  7673. return null;
  7674. };
  7675. Scene.prototype.getGeometryByID = function (id) {
  7676. for (var index = 0; index < this._geometries.length; index++) {
  7677. if (this._geometries[index].id === id) {
  7678. return this._geometries[index];
  7679. }
  7680. }
  7681. return null;
  7682. };
  7683. Scene.prototype.pushGeometry = function (geometry, force) {
  7684. if (!force && this.getGeometryByID(geometry.id)) {
  7685. return false;
  7686. }
  7687. this._geometries.push(geometry);
  7688. return true;
  7689. };
  7690. Scene.prototype.getGeometries = function () {
  7691. return this._geometries;
  7692. };
  7693. Scene.prototype.getMeshByID = function (id) {
  7694. for (var index = 0; index < this.meshes.length; index++) {
  7695. if (this.meshes[index].id === id) {
  7696. return this.meshes[index];
  7697. }
  7698. }
  7699. return null;
  7700. };
  7701. Scene.prototype.getLastMeshByID = function (id) {
  7702. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7703. if (this.meshes[index].id === id) {
  7704. return this.meshes[index];
  7705. }
  7706. }
  7707. return null;
  7708. };
  7709. Scene.prototype.getLastEntryByID = function (id) {
  7710. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7711. if (this.meshes[index].id === id) {
  7712. return this.meshes[index];
  7713. }
  7714. }
  7715. for (index = this.cameras.length - 1; index >= 0; index--) {
  7716. if (this.cameras[index].id === id) {
  7717. return this.cameras[index];
  7718. }
  7719. }
  7720. for (index = this.lights.length - 1; index >= 0; index--) {
  7721. if (this.lights[index].id === id) {
  7722. return this.lights[index];
  7723. }
  7724. }
  7725. return null;
  7726. };
  7727. Scene.prototype.getNodeByName = function (name) {
  7728. var mesh = this.getMeshByName(name);
  7729. if (mesh) {
  7730. return mesh;
  7731. }
  7732. var light = this.getLightByName(name);
  7733. if (light) {
  7734. return light;
  7735. }
  7736. return this.getCameraByName(name);
  7737. };
  7738. Scene.prototype.getMeshByName = function (name) {
  7739. for (var index = 0; index < this.meshes.length; index++) {
  7740. if (this.meshes[index].name === name) {
  7741. return this.meshes[index];
  7742. }
  7743. }
  7744. return null;
  7745. };
  7746. Scene.prototype.getLastSkeletonByID = function (id) {
  7747. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7748. if (this.skeletons[index].id === id) {
  7749. return this.skeletons[index];
  7750. }
  7751. }
  7752. return null;
  7753. };
  7754. Scene.prototype.getSkeletonById = function (id) {
  7755. for (var index = 0; index < this.skeletons.length; index++) {
  7756. if (this.skeletons[index].id === id) {
  7757. return this.skeletons[index];
  7758. }
  7759. }
  7760. return null;
  7761. };
  7762. Scene.prototype.getSkeletonByName = function (name) {
  7763. for (var index = 0; index < this.skeletons.length; index++) {
  7764. if (this.skeletons[index].name === name) {
  7765. return this.skeletons[index];
  7766. }
  7767. }
  7768. return null;
  7769. };
  7770. Scene.prototype.isActiveMesh = function (mesh) {
  7771. return (this._activeMeshes.indexOf(mesh) !== -1);
  7772. };
  7773. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7774. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7775. var material = subMesh.getMaterial();
  7776. if (mesh.showSubMeshesBoundingBox) {
  7777. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7778. }
  7779. if (material) {
  7780. // Render targets
  7781. if (material.getRenderTargetTextures) {
  7782. if (this._processedMaterials.indexOf(material) === -1) {
  7783. this._processedMaterials.push(material);
  7784. this._renderTargets.concat(material.getRenderTargetTextures());
  7785. }
  7786. }
  7787. // Dispatch
  7788. this._activeVertices += subMesh.indexCount;
  7789. this._renderingManager.dispatch(subMesh);
  7790. }
  7791. }
  7792. };
  7793. Scene.prototype._evaluateActiveMeshes = function () {
  7794. this._activeMeshes.reset();
  7795. this._renderingManager.reset();
  7796. this._processedMaterials.reset();
  7797. this._activeParticleSystems.reset();
  7798. this._activeSkeletons.reset();
  7799. this._boundingBoxRenderer.reset();
  7800. if (!this._frustumPlanes) {
  7801. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7802. } else {
  7803. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7804. }
  7805. // Meshes
  7806. var meshes;
  7807. var len;
  7808. if (this._selectionOctree) {
  7809. var selection = this._selectionOctree.select(this._frustumPlanes);
  7810. meshes = selection.data;
  7811. len = selection.length;
  7812. } else {
  7813. len = this.meshes.length;
  7814. meshes = this.meshes;
  7815. }
  7816. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7817. var mesh = meshes[meshIndex];
  7818. if (mesh.isBlocked) {
  7819. continue;
  7820. }
  7821. this._totalVertices += mesh.getTotalVertices();
  7822. if (!mesh.isReady()) {
  7823. continue;
  7824. }
  7825. mesh.computeWorldMatrix();
  7826. // Intersections
  7827. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7828. this._meshesForIntersections.pushNoDuplicate(mesh);
  7829. }
  7830. // Switch to current LOD
  7831. var meshLOD = mesh.getLOD(this.activeCamera);
  7832. if (!meshLOD) {
  7833. continue;
  7834. }
  7835. mesh._preActivate();
  7836. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7837. this._activeMeshes.push(mesh);
  7838. mesh._activate(this._renderId);
  7839. this._activeMesh(meshLOD);
  7840. }
  7841. }
  7842. // Particle systems
  7843. var beforeParticlesDate = BABYLON.Tools.Now;
  7844. if (this.particlesEnabled) {
  7845. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7846. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7847. var particleSystem = this.particleSystems[particleIndex];
  7848. if (!particleSystem.isStarted()) {
  7849. continue;
  7850. }
  7851. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7852. this._activeParticleSystems.push(particleSystem);
  7853. particleSystem.animate();
  7854. }
  7855. }
  7856. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7857. }
  7858. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7859. };
  7860. Scene.prototype._activeMesh = function (mesh) {
  7861. if (mesh.skeleton && this.skeletonsEnabled) {
  7862. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7863. }
  7864. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  7865. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7866. }
  7867. if (mesh && mesh.subMeshes) {
  7868. // Submeshes Octrees
  7869. var len;
  7870. var subMeshes;
  7871. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7872. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7873. len = intersections.length;
  7874. subMeshes = intersections.data;
  7875. } else {
  7876. subMeshes = mesh.subMeshes;
  7877. len = subMeshes.length;
  7878. }
  7879. for (var subIndex = 0; subIndex < len; subIndex++) {
  7880. var subMesh = subMeshes[subIndex];
  7881. this._evaluateSubMesh(subMesh, mesh);
  7882. }
  7883. }
  7884. };
  7885. Scene.prototype.updateTransformMatrix = function (force) {
  7886. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7887. };
  7888. Scene.prototype._renderForCamera = function (camera) {
  7889. var engine = this._engine;
  7890. this.activeCamera = camera;
  7891. if (!this.activeCamera)
  7892. throw new Error("Active camera not set");
  7893. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7894. // Viewport
  7895. engine.setViewport(this.activeCamera.viewport);
  7896. // Camera
  7897. this._renderId++;
  7898. this.updateTransformMatrix();
  7899. if (this.beforeCameraRender) {
  7900. this.beforeCameraRender(this.activeCamera);
  7901. }
  7902. // Meshes
  7903. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7904. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7905. this._evaluateActiveMeshes();
  7906. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7907. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7908. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7909. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7910. skeleton.prepare();
  7911. this._activeBones += skeleton.bones.length;
  7912. }
  7913. // Render targets
  7914. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7915. if (this.renderTargetsEnabled) {
  7916. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7917. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7918. var renderTarget = this._renderTargets.data[renderIndex];
  7919. if (renderTarget._shouldRender()) {
  7920. this._renderId++;
  7921. renderTarget.render();
  7922. }
  7923. }
  7924. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7925. this._renderId++;
  7926. }
  7927. if (this._renderTargets.length > 0) {
  7928. engine.restoreDefaultFramebuffer();
  7929. }
  7930. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7931. // Prepare Frame
  7932. this.postProcessManager._prepareFrame();
  7933. var beforeRenderDate = BABYLON.Tools.Now;
  7934. // Backgrounds
  7935. if (this.layers.length) {
  7936. engine.setDepthBuffer(false);
  7937. var layerIndex;
  7938. var layer;
  7939. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7940. layer = this.layers[layerIndex];
  7941. if (layer.isBackground) {
  7942. layer.render();
  7943. }
  7944. }
  7945. engine.setDepthBuffer(true);
  7946. }
  7947. // Render
  7948. BABYLON.Tools.StartPerformanceCounter("Main render");
  7949. this._renderingManager.render(null, null, true, true);
  7950. BABYLON.Tools.EndPerformanceCounter("Main render");
  7951. // Bounding boxes
  7952. this._boundingBoxRenderer.render();
  7953. // Lens flares
  7954. if (this.lensFlaresEnabled) {
  7955. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7956. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7957. this.lensFlareSystems[lensFlareSystemIndex].render();
  7958. }
  7959. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7960. }
  7961. // Foregrounds
  7962. if (this.layers.length) {
  7963. engine.setDepthBuffer(false);
  7964. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7965. layer = this.layers[layerIndex];
  7966. if (!layer.isBackground) {
  7967. layer.render();
  7968. }
  7969. }
  7970. engine.setDepthBuffer(true);
  7971. }
  7972. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7973. // Finalize frame
  7974. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7975. // Update camera
  7976. this.activeCamera._updateFromScene();
  7977. // Reset some special arrays
  7978. this._renderTargets.reset();
  7979. if (this.afterCameraRender) {
  7980. this.afterCameraRender(this.activeCamera);
  7981. }
  7982. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7983. };
  7984. Scene.prototype._processSubCameras = function (camera) {
  7985. if (camera.subCameras.length === 0) {
  7986. this._renderForCamera(camera);
  7987. return;
  7988. }
  7989. for (var index = 0; index < camera.subCameras.length; index++) {
  7990. this._renderForCamera(camera.subCameras[index]);
  7991. }
  7992. this.activeCamera = camera;
  7993. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7994. // Update camera
  7995. this.activeCamera._updateFromScene();
  7996. };
  7997. Scene.prototype._checkIntersections = function () {
  7998. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7999. var sourceMesh = this._meshesForIntersections.data[index];
  8000. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8001. var action = sourceMesh.actionManager.actions[actionIndex];
  8002. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8003. var otherMesh = action.getTriggerParameter();
  8004. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  8005. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8006. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8007. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8008. sourceMesh._intersectionsInProgress.push(otherMesh);
  8009. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8010. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8011. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8012. if (indexOfOther > -1) {
  8013. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8014. }
  8015. }
  8016. }
  8017. }
  8018. }
  8019. };
  8020. Scene.prototype.render = function () {
  8021. var startDate = BABYLON.Tools.Now;
  8022. this._particlesDuration = 0;
  8023. this._spritesDuration = 0;
  8024. this._activeParticles = 0;
  8025. this._renderDuration = 0;
  8026. this._renderTargetsDuration = 0;
  8027. this._evaluateActiveMeshesDuration = 0;
  8028. this._totalVertices = 0;
  8029. this._activeVertices = 0;
  8030. this._activeBones = 0;
  8031. this.getEngine().resetDrawCalls();
  8032. this._meshesForIntersections.reset();
  8033. this.resetCachedMaterial();
  8034. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8035. // Actions
  8036. if (this.actionManager) {
  8037. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8038. }
  8039. // Before render
  8040. if (this.beforeRender) {
  8041. this.beforeRender();
  8042. }
  8043. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8044. this._onBeforeRenderCallbacks[callbackIndex]();
  8045. }
  8046. // Animations
  8047. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8048. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8049. this._animate();
  8050. // Physics
  8051. if (this._physicsEngine) {
  8052. BABYLON.Tools.StartPerformanceCounter("Physics");
  8053. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8054. BABYLON.Tools.EndPerformanceCounter("Physics");
  8055. }
  8056. // Customs render targets
  8057. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8058. var engine = this.getEngine();
  8059. if (this.renderTargetsEnabled) {
  8060. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8061. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8062. var renderTarget = this.customRenderTargets[customIndex];
  8063. if (renderTarget._shouldRender()) {
  8064. this._renderId++;
  8065. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8066. if (!this.activeCamera)
  8067. throw new Error("Active camera not set");
  8068. // Viewport
  8069. engine.setViewport(this.activeCamera.viewport);
  8070. // Camera
  8071. this.updateTransformMatrix();
  8072. renderTarget.render();
  8073. }
  8074. }
  8075. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8076. this._renderId++;
  8077. }
  8078. if (this.customRenderTargets.length > 0) {
  8079. engine.restoreDefaultFramebuffer();
  8080. }
  8081. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8082. // Procedural textures
  8083. if (this.proceduralTexturesEnabled) {
  8084. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8085. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8086. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8087. if (proceduralTexture._shouldRender()) {
  8088. proceduralTexture.render();
  8089. }
  8090. }
  8091. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8092. }
  8093. // Clear
  8094. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8095. // Shadows
  8096. if (this.shadowsEnabled) {
  8097. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8098. var light = this.lights[lightIndex];
  8099. var shadowGenerator = light.getShadowGenerator();
  8100. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8101. this._renderTargets.push(shadowGenerator.getShadowMap());
  8102. }
  8103. }
  8104. }
  8105. // RenderPipeline
  8106. this.postProcessRenderPipelineManager.update();
  8107. // Multi-cameras?
  8108. if (this.activeCameras.length > 0) {
  8109. var currentRenderId = this._renderId;
  8110. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8111. this._renderId = currentRenderId;
  8112. this._processSubCameras(this.activeCameras[cameraIndex]);
  8113. }
  8114. } else {
  8115. if (!this.activeCamera) {
  8116. throw new Error("No camera defined");
  8117. }
  8118. this._processSubCameras(this.activeCamera);
  8119. }
  8120. // Intersection checks
  8121. this._checkIntersections();
  8122. // Update the audio listener attached to the camera
  8123. this._updateAudioParameters();
  8124. // After render
  8125. if (this.afterRender) {
  8126. this.afterRender();
  8127. }
  8128. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8129. this._onAfterRenderCallbacks[callbackIndex]();
  8130. }
  8131. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8132. this._toBeDisposed.data[index].dispose();
  8133. this._toBeDisposed[index] = null;
  8134. }
  8135. this._toBeDisposed.reset();
  8136. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8137. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8138. };
  8139. Scene.prototype._updateAudioParameters = function () {
  8140. var listeningCamera;
  8141. var audioEngine = this._engine.getAudioEngine();
  8142. if (this.activeCameras.length > 0) {
  8143. listeningCamera = this.activeCameras[0];
  8144. } else {
  8145. listeningCamera = this.activeCamera;
  8146. }
  8147. if (listeningCamera && audioEngine.canUseWebAudio) {
  8148. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8149. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8150. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8151. cameraDirection.normalize();
  8152. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8153. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8154. var sound = this.mainSoundTrack.soundCollection[i];
  8155. if (sound.useCustomAttenuation) {
  8156. sound.updateDistanceFromListener();
  8157. }
  8158. }
  8159. for (var i = 0; i < this.soundTracks.length; i++) {
  8160. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8161. var sound = this.soundTracks[i].soundCollection[j];
  8162. if (sound.useCustomAttenuation) {
  8163. sound.updateDistanceFromListener();
  8164. }
  8165. }
  8166. }
  8167. }
  8168. };
  8169. Scene.prototype.dispose = function () {
  8170. this.beforeRender = null;
  8171. this.afterRender = null;
  8172. this.skeletons = [];
  8173. this._boundingBoxRenderer.dispose();
  8174. // Debug layer
  8175. this.debugLayer.hide();
  8176. // Events
  8177. if (this.onDispose) {
  8178. this.onDispose();
  8179. }
  8180. this._onBeforeRenderCallbacks = [];
  8181. this._onAfterRenderCallbacks = [];
  8182. this.detachControl();
  8183. // Detach cameras
  8184. var canvas = this._engine.getRenderingCanvas();
  8185. var index;
  8186. for (index = 0; index < this.cameras.length; index++) {
  8187. this.cameras[index].detachControl(canvas);
  8188. }
  8189. while (this.lights.length) {
  8190. this.lights[0].dispose();
  8191. }
  8192. while (this.meshes.length) {
  8193. this.meshes[0].dispose(true);
  8194. }
  8195. while (this.cameras.length) {
  8196. this.cameras[0].dispose();
  8197. }
  8198. while (this.materials.length) {
  8199. this.materials[0].dispose();
  8200. }
  8201. while (this.particleSystems.length) {
  8202. this.particleSystems[0].dispose();
  8203. }
  8204. while (this.spriteManagers.length) {
  8205. this.spriteManagers[0].dispose();
  8206. }
  8207. while (this.layers.length) {
  8208. this.layers[0].dispose();
  8209. }
  8210. while (this.textures.length) {
  8211. this.textures[0].dispose();
  8212. }
  8213. // Post-processes
  8214. this.postProcessManager.dispose();
  8215. // Physics
  8216. if (this._physicsEngine) {
  8217. this.disablePhysicsEngine();
  8218. }
  8219. // Remove from engine
  8220. index = this._engine.scenes.indexOf(this);
  8221. if (index > -1) {
  8222. this._engine.scenes.splice(index, 1);
  8223. }
  8224. this._engine.wipeCaches();
  8225. };
  8226. // Collisions
  8227. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8228. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8229. position.divideToRef(collider.radius, this._scaledPosition);
  8230. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8231. collider.retry = 0;
  8232. collider.initialVelocity = this._scaledVelocity;
  8233. collider.initialPosition = this._scaledPosition;
  8234. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8235. finalPosition.multiplyInPlace(collider.radius);
  8236. };
  8237. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8238. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8239. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8240. if (collider.retry >= maximumRetry) {
  8241. finalPosition.copyFrom(position);
  8242. return;
  8243. }
  8244. collider._initialize(position, velocity, closeDistance);
  8245. for (var index = 0; index < this.meshes.length; index++) {
  8246. var mesh = this.meshes[index];
  8247. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8248. mesh._checkCollision(collider);
  8249. }
  8250. }
  8251. if (!collider.collisionFound) {
  8252. position.addToRef(velocity, finalPosition);
  8253. return;
  8254. }
  8255. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8256. collider._getResponse(position, velocity);
  8257. }
  8258. if (velocity.length() <= closeDistance) {
  8259. finalPosition.copyFrom(position);
  8260. return;
  8261. }
  8262. collider.retry++;
  8263. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8264. };
  8265. // Octrees
  8266. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8267. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8268. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8269. if (!this._selectionOctree) {
  8270. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8271. }
  8272. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8273. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8274. for (var index = 0; index < this.meshes.length; index++) {
  8275. var mesh = this.meshes[index];
  8276. mesh.computeWorldMatrix(true);
  8277. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8278. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8279. BABYLON.Tools.CheckExtends(minBox, min, max);
  8280. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8281. }
  8282. // Update octree
  8283. this._selectionOctree.update(min, max, this.meshes);
  8284. return this._selectionOctree;
  8285. };
  8286. // Picking
  8287. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8288. var engine = this._engine;
  8289. if (!camera) {
  8290. if (!this.activeCamera)
  8291. throw new Error("Active camera not set");
  8292. camera = this.activeCamera;
  8293. }
  8294. var cameraViewport = camera.viewport;
  8295. var viewport = cameraViewport.toGlobal(engine);
  8296. // Moving coordinates to local viewport world
  8297. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8298. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8299. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8300. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8301. };
  8302. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8303. var pickingInfo = null;
  8304. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8305. var mesh = this.meshes[meshIndex];
  8306. if (predicate) {
  8307. if (!predicate(mesh)) {
  8308. continue;
  8309. }
  8310. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8311. continue;
  8312. }
  8313. var world = mesh.getWorldMatrix();
  8314. var ray = rayFunction(world);
  8315. var result = mesh.intersects(ray, fastCheck);
  8316. if (!result || !result.hit)
  8317. continue;
  8318. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8319. continue;
  8320. pickingInfo = result;
  8321. if (fastCheck) {
  8322. break;
  8323. }
  8324. }
  8325. return pickingInfo || new BABYLON.PickingInfo();
  8326. };
  8327. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8328. var _this = this;
  8329. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8330. /// <param name="x">X position on screen</param>
  8331. /// <param name="y">Y position on screen</param>
  8332. /// <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>
  8333. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8334. /// <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>
  8335. return this._internalPick(function (world) {
  8336. return _this.createPickingRay(x, y, world, camera);
  8337. }, predicate, fastCheck);
  8338. };
  8339. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8340. var _this = this;
  8341. return this._internalPick(function (world) {
  8342. if (!_this._pickWithRayInverseMatrix) {
  8343. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8344. }
  8345. world.invertToRef(_this._pickWithRayInverseMatrix);
  8346. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8347. }, predicate, fastCheck);
  8348. };
  8349. Scene.prototype.setPointerOverMesh = function (mesh) {
  8350. if (this._pointerOverMesh === mesh) {
  8351. return;
  8352. }
  8353. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8354. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8355. }
  8356. this._pointerOverMesh = mesh;
  8357. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8358. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8359. }
  8360. };
  8361. Scene.prototype.getPointerOverMesh = function () {
  8362. return this._pointerOverMesh;
  8363. };
  8364. // Physics
  8365. Scene.prototype.getPhysicsEngine = function () {
  8366. return this._physicsEngine;
  8367. };
  8368. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8369. if (this._physicsEngine) {
  8370. return true;
  8371. }
  8372. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8373. if (!this._physicsEngine.isSupported()) {
  8374. this._physicsEngine = null;
  8375. return false;
  8376. }
  8377. this._physicsEngine._initialize(gravity);
  8378. return true;
  8379. };
  8380. Scene.prototype.disablePhysicsEngine = function () {
  8381. if (!this._physicsEngine) {
  8382. return;
  8383. }
  8384. this._physicsEngine.dispose();
  8385. this._physicsEngine = undefined;
  8386. };
  8387. Scene.prototype.isPhysicsEnabled = function () {
  8388. return this._physicsEngine !== undefined;
  8389. };
  8390. Scene.prototype.setGravity = function (gravity) {
  8391. if (!this._physicsEngine) {
  8392. return;
  8393. }
  8394. this._physicsEngine._setGravity(gravity);
  8395. };
  8396. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8397. if (parts.parts) {
  8398. options = parts;
  8399. parts = parts.parts;
  8400. }
  8401. if (!this._physicsEngine) {
  8402. return null;
  8403. }
  8404. for (var index = 0; index < parts.length; index++) {
  8405. var mesh = parts[index].mesh;
  8406. mesh._physicImpostor = parts[index].impostor;
  8407. mesh._physicsMass = options.mass / parts.length;
  8408. mesh._physicsFriction = options.friction;
  8409. mesh._physicRestitution = options.restitution;
  8410. }
  8411. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8412. };
  8413. //ANY
  8414. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8415. for (var index = 0; index < compound.parts.length; index++) {
  8416. var mesh = compound.parts[index].mesh;
  8417. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8418. this._physicsEngine._unregisterMesh(mesh);
  8419. }
  8420. };
  8421. // Tags
  8422. Scene.prototype._getByTags = function (list, tagsQuery) {
  8423. if (tagsQuery === undefined) {
  8424. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8425. return list;
  8426. }
  8427. var listByTags = [];
  8428. for (var i in list) {
  8429. var item = list[i];
  8430. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8431. listByTags.push(item);
  8432. }
  8433. }
  8434. return listByTags;
  8435. };
  8436. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  8437. return this._getByTags(this.meshes, tagsQuery);
  8438. };
  8439. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  8440. return this._getByTags(this.cameras, tagsQuery);
  8441. };
  8442. Scene.prototype.getLightsByTags = function (tagsQuery) {
  8443. return this._getByTags(this.lights, tagsQuery);
  8444. };
  8445. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  8446. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  8447. };
  8448. Scene.FOGMODE_NONE = 0;
  8449. Scene.FOGMODE_EXP = 1;
  8450. Scene.FOGMODE_EXP2 = 2;
  8451. Scene.FOGMODE_LINEAR = 3;
  8452. Scene.MinDeltaTime = 1.0;
  8453. Scene.MaxDeltaTime = 1000.0;
  8454. return Scene;
  8455. })();
  8456. BABYLON.Scene = Scene;
  8457. })(BABYLON || (BABYLON = {}));
  8458. //# sourceMappingURL=babylon.scene.js.map
  8459. var BABYLON;
  8460. (function (BABYLON) {
  8461. var VertexBuffer = (function () {
  8462. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8463. if (engine instanceof BABYLON.Mesh) {
  8464. this._engine = engine.getScene().getEngine();
  8465. } else {
  8466. this._engine = engine;
  8467. }
  8468. this._updatable = updatable;
  8469. this._data = data;
  8470. if (!postponeInternalCreation) {
  8471. this.create();
  8472. }
  8473. this._kind = kind;
  8474. if (stride) {
  8475. this._strideSize = stride;
  8476. return;
  8477. }
  8478. switch (kind) {
  8479. case VertexBuffer.PositionKind:
  8480. this._strideSize = 3;
  8481. break;
  8482. case VertexBuffer.NormalKind:
  8483. this._strideSize = 3;
  8484. break;
  8485. case VertexBuffer.UVKind:
  8486. this._strideSize = 2;
  8487. break;
  8488. case VertexBuffer.UV2Kind:
  8489. this._strideSize = 2;
  8490. break;
  8491. case VertexBuffer.ColorKind:
  8492. this._strideSize = 4;
  8493. break;
  8494. case VertexBuffer.MatricesIndicesKind:
  8495. this._strideSize = 4;
  8496. break;
  8497. case VertexBuffer.MatricesWeightsKind:
  8498. this._strideSize = 4;
  8499. break;
  8500. }
  8501. }
  8502. // Properties
  8503. VertexBuffer.prototype.isUpdatable = function () {
  8504. return this._updatable;
  8505. };
  8506. VertexBuffer.prototype.getData = function () {
  8507. return this._data;
  8508. };
  8509. VertexBuffer.prototype.getBuffer = function () {
  8510. return this._buffer;
  8511. };
  8512. VertexBuffer.prototype.getStrideSize = function () {
  8513. return this._strideSize;
  8514. };
  8515. // Methods
  8516. VertexBuffer.prototype.create = function (data) {
  8517. if (!data && this._buffer) {
  8518. return;
  8519. }
  8520. data = data || this._data;
  8521. if (!this._buffer) {
  8522. if (this._updatable) {
  8523. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8524. } else {
  8525. this._buffer = this._engine.createVertexBuffer(data);
  8526. }
  8527. }
  8528. if (this._updatable) {
  8529. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8530. this._data = data;
  8531. }
  8532. };
  8533. VertexBuffer.prototype.update = function (data) {
  8534. this.create(data);
  8535. };
  8536. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8537. if (!this._buffer) {
  8538. return;
  8539. }
  8540. if (this._updatable) {
  8541. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8542. this._data = null;
  8543. }
  8544. };
  8545. VertexBuffer.prototype.dispose = function () {
  8546. if (!this._buffer) {
  8547. return;
  8548. }
  8549. if (this._engine._releaseBuffer(this._buffer)) {
  8550. this._buffer = null;
  8551. }
  8552. };
  8553. Object.defineProperty(VertexBuffer, "PositionKind", {
  8554. get: function () {
  8555. return VertexBuffer._PositionKind;
  8556. },
  8557. enumerable: true,
  8558. configurable: true
  8559. });
  8560. Object.defineProperty(VertexBuffer, "NormalKind", {
  8561. get: function () {
  8562. return VertexBuffer._NormalKind;
  8563. },
  8564. enumerable: true,
  8565. configurable: true
  8566. });
  8567. Object.defineProperty(VertexBuffer, "UVKind", {
  8568. get: function () {
  8569. return VertexBuffer._UVKind;
  8570. },
  8571. enumerable: true,
  8572. configurable: true
  8573. });
  8574. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8575. get: function () {
  8576. return VertexBuffer._UV2Kind;
  8577. },
  8578. enumerable: true,
  8579. configurable: true
  8580. });
  8581. Object.defineProperty(VertexBuffer, "ColorKind", {
  8582. get: function () {
  8583. return VertexBuffer._ColorKind;
  8584. },
  8585. enumerable: true,
  8586. configurable: true
  8587. });
  8588. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8589. get: function () {
  8590. return VertexBuffer._MatricesIndicesKind;
  8591. },
  8592. enumerable: true,
  8593. configurable: true
  8594. });
  8595. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8596. get: function () {
  8597. return VertexBuffer._MatricesWeightsKind;
  8598. },
  8599. enumerable: true,
  8600. configurable: true
  8601. });
  8602. VertexBuffer._PositionKind = "position";
  8603. VertexBuffer._NormalKind = "normal";
  8604. VertexBuffer._UVKind = "uv";
  8605. VertexBuffer._UV2Kind = "uv2";
  8606. VertexBuffer._ColorKind = "color";
  8607. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8608. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8609. return VertexBuffer;
  8610. })();
  8611. BABYLON.VertexBuffer = VertexBuffer;
  8612. })(BABYLON || (BABYLON = {}));
  8613. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8614. var BABYLON;
  8615. (function (BABYLON) {
  8616. var AbstractMesh = (function (_super) {
  8617. __extends(AbstractMesh, _super);
  8618. function AbstractMesh(name, scene) {
  8619. _super.call(this, name, scene);
  8620. // Properties
  8621. this.position = new BABYLON.Vector3(0, 0, 0);
  8622. this.rotation = new BABYLON.Vector3(0, 0, 0);
  8623. this.scaling = new BABYLON.Vector3(1, 1, 1);
  8624. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8625. this.visibility = 1.0;
  8626. this.alphaIndex = Number.MAX_VALUE;
  8627. this.infiniteDistance = false;
  8628. this.isVisible = true;
  8629. this.isPickable = true;
  8630. this.showBoundingBox = false;
  8631. this.showSubMeshesBoundingBox = false;
  8632. this.onDispose = null;
  8633. this.checkCollisions = false;
  8634. this.isBlocker = false;
  8635. this.renderingGroupId = 0;
  8636. this.receiveShadows = false;
  8637. this.renderOutline = false;
  8638. this.outlineColor = BABYLON.Color3.Red();
  8639. this.outlineWidth = 0.02;
  8640. this.renderOverlay = false;
  8641. this.overlayColor = BABYLON.Color3.Red();
  8642. this.overlayAlpha = 0.5;
  8643. this.hasVertexAlpha = false;
  8644. this.useVertexColors = true;
  8645. this.applyFog = true;
  8646. this.useOctreeForRenderingSelection = true;
  8647. this.useOctreeForPicking = true;
  8648. this.useOctreeForCollisions = true;
  8649. this.layerMask = 0xFFFFFFFF;
  8650. // Physics
  8651. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8652. // Collisions
  8653. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8654. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8655. this._collider = new BABYLON.Collider();
  8656. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8657. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8658. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8659. // Cache
  8660. this._localScaling = BABYLON.Matrix.Zero();
  8661. this._localRotation = BABYLON.Matrix.Zero();
  8662. this._localTranslation = BABYLON.Matrix.Zero();
  8663. this._localBillboard = BABYLON.Matrix.Zero();
  8664. this._localPivotScaling = BABYLON.Matrix.Zero();
  8665. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  8666. this._localWorld = BABYLON.Matrix.Zero();
  8667. this._worldMatrix = BABYLON.Matrix.Zero();
  8668. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8669. this._absolutePosition = BABYLON.Vector3.Zero();
  8670. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8671. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8672. this._isDirty = false;
  8673. this._pivotMatrix = BABYLON.Matrix.Identity();
  8674. this._isDisposed = false;
  8675. this._renderId = 0;
  8676. this._intersectionsInProgress = new Array();
  8677. this._onAfterWorldMatrixUpdate = new Array();
  8678. scene.meshes.push(this);
  8679. }
  8680. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8681. get: function () {
  8682. return AbstractMesh._BILLBOARDMODE_NONE;
  8683. },
  8684. enumerable: true,
  8685. configurable: true
  8686. });
  8687. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8688. get: function () {
  8689. return AbstractMesh._BILLBOARDMODE_X;
  8690. },
  8691. enumerable: true,
  8692. configurable: true
  8693. });
  8694. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8695. get: function () {
  8696. return AbstractMesh._BILLBOARDMODE_Y;
  8697. },
  8698. enumerable: true,
  8699. configurable: true
  8700. });
  8701. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8702. get: function () {
  8703. return AbstractMesh._BILLBOARDMODE_Z;
  8704. },
  8705. enumerable: true,
  8706. configurable: true
  8707. });
  8708. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8709. get: function () {
  8710. return AbstractMesh._BILLBOARDMODE_ALL;
  8711. },
  8712. enumerable: true,
  8713. configurable: true
  8714. });
  8715. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8716. // Methods
  8717. get: function () {
  8718. return false;
  8719. },
  8720. enumerable: true,
  8721. configurable: true
  8722. });
  8723. AbstractMesh.prototype.getLOD = function (camera) {
  8724. return this;
  8725. };
  8726. AbstractMesh.prototype.getTotalVertices = function () {
  8727. return 0;
  8728. };
  8729. AbstractMesh.prototype.getIndices = function () {
  8730. return null;
  8731. };
  8732. AbstractMesh.prototype.getVerticesData = function (kind) {
  8733. return null;
  8734. };
  8735. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8736. return false;
  8737. };
  8738. AbstractMesh.prototype.getBoundingInfo = function () {
  8739. if (this._masterMesh) {
  8740. return this._masterMesh.getBoundingInfo();
  8741. }
  8742. if (!this._boundingInfo) {
  8743. this._updateBoundingInfo();
  8744. }
  8745. return this._boundingInfo;
  8746. };
  8747. AbstractMesh.prototype._preActivate = function () {
  8748. };
  8749. AbstractMesh.prototype._activate = function (renderId) {
  8750. this._renderId = renderId;
  8751. };
  8752. AbstractMesh.prototype.getWorldMatrix = function () {
  8753. if (this._masterMesh) {
  8754. return this._masterMesh.getWorldMatrix();
  8755. }
  8756. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8757. this.computeWorldMatrix();
  8758. }
  8759. return this._worldMatrix;
  8760. };
  8761. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8762. get: function () {
  8763. return this._worldMatrix;
  8764. },
  8765. enumerable: true,
  8766. configurable: true
  8767. });
  8768. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8769. get: function () {
  8770. return this._absolutePosition;
  8771. },
  8772. enumerable: true,
  8773. configurable: true
  8774. });
  8775. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8776. if (!this.rotationQuaternion) {
  8777. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8778. this.rotation = BABYLON.Vector3.Zero();
  8779. }
  8780. if (!space || space == 0 /* LOCAL */) {
  8781. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8782. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8783. } else {
  8784. if (this.parent) {
  8785. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8786. invertParentWorldMatrix.invert();
  8787. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8788. }
  8789. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8790. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8791. }
  8792. };
  8793. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8794. var displacementVector = axis.scale(distance);
  8795. if (!space || space == 0 /* LOCAL */) {
  8796. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8797. this.setPositionWithLocalVector(tempV3);
  8798. } else {
  8799. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8800. }
  8801. };
  8802. AbstractMesh.prototype.getAbsolutePosition = function () {
  8803. this.computeWorldMatrix();
  8804. return this._absolutePosition;
  8805. };
  8806. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8807. if (!absolutePosition) {
  8808. return;
  8809. }
  8810. var absolutePositionX;
  8811. var absolutePositionY;
  8812. var absolutePositionZ;
  8813. if (absolutePosition.x === undefined) {
  8814. if (arguments.length < 3) {
  8815. return;
  8816. }
  8817. absolutePositionX = arguments[0];
  8818. absolutePositionY = arguments[1];
  8819. absolutePositionZ = arguments[2];
  8820. } else {
  8821. absolutePositionX = absolutePosition.x;
  8822. absolutePositionY = absolutePosition.y;
  8823. absolutePositionZ = absolutePosition.z;
  8824. }
  8825. if (this.parent) {
  8826. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8827. invertParentWorldMatrix.invert();
  8828. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8829. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8830. } else {
  8831. this.position.x = absolutePositionX;
  8832. this.position.y = absolutePositionY;
  8833. this.position.z = absolutePositionZ;
  8834. }
  8835. };
  8836. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8837. this._pivotMatrix = matrix;
  8838. this._cache.pivotMatrixUpdated = true;
  8839. };
  8840. AbstractMesh.prototype.getPivotMatrix = function () {
  8841. return this._pivotMatrix;
  8842. };
  8843. AbstractMesh.prototype._isSynchronized = function () {
  8844. if (this._isDirty) {
  8845. return false;
  8846. }
  8847. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8848. return false;
  8849. if (this._cache.pivotMatrixUpdated) {
  8850. return false;
  8851. }
  8852. if (this.infiniteDistance) {
  8853. return false;
  8854. }
  8855. if (!this._cache.position.equals(this.position))
  8856. return false;
  8857. if (this.rotationQuaternion) {
  8858. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8859. return false;
  8860. } else {
  8861. if (!this._cache.rotation.equals(this.rotation))
  8862. return false;
  8863. }
  8864. if (!this._cache.scaling.equals(this.scaling))
  8865. return false;
  8866. return true;
  8867. };
  8868. AbstractMesh.prototype._initCache = function () {
  8869. _super.prototype._initCache.call(this);
  8870. this._cache.localMatrixUpdated = false;
  8871. this._cache.position = BABYLON.Vector3.Zero();
  8872. this._cache.scaling = BABYLON.Vector3.Zero();
  8873. this._cache.rotation = BABYLON.Vector3.Zero();
  8874. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8875. };
  8876. AbstractMesh.prototype.markAsDirty = function (property) {
  8877. if (property === "rotation") {
  8878. this.rotationQuaternion = null;
  8879. }
  8880. this._currentRenderId = Number.MAX_VALUE;
  8881. this._isDirty = true;
  8882. };
  8883. AbstractMesh.prototype._updateBoundingInfo = function () {
  8884. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8885. this._boundingInfo._update(this.worldMatrixFromCache);
  8886. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8887. };
  8888. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8889. if (!this.subMeshes) {
  8890. return;
  8891. }
  8892. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8893. var subMesh = this.subMeshes[subIndex];
  8894. subMesh.updateBoundingInfo(matrix);
  8895. }
  8896. };
  8897. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8898. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8899. return this._worldMatrix;
  8900. }
  8901. this._cache.position.copyFrom(this.position);
  8902. this._cache.scaling.copyFrom(this.scaling);
  8903. this._cache.pivotMatrixUpdated = false;
  8904. this._currentRenderId = this.getScene().getRenderId();
  8905. this._isDirty = false;
  8906. // Scaling
  8907. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8908. // Rotation
  8909. if (this.rotationQuaternion) {
  8910. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8911. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8912. } else {
  8913. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8914. this._cache.rotation.copyFrom(this.rotation);
  8915. }
  8916. // Translation
  8917. if (this.infiniteDistance && !this.parent) {
  8918. var camera = this.getScene().activeCamera;
  8919. var cameraWorldMatrix = camera.getWorldMatrix();
  8920. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8921. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8922. } else {
  8923. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8924. }
  8925. // Composing transformations
  8926. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8927. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8928. // Billboarding
  8929. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8930. var localPosition = this.position.clone();
  8931. var zero = this.getScene().activeCamera.position.clone();
  8932. if (this.parent && this.parent.position) {
  8933. localPosition.addInPlace(this.parent.position);
  8934. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8935. }
  8936. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  8937. zero = this.getScene().activeCamera.position;
  8938. } else {
  8939. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  8940. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8941. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  8942. zero.y = localPosition.y + 0.001;
  8943. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  8944. zero.z = localPosition.z + 0.001;
  8945. }
  8946. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8947. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8948. this._localBillboard.invert();
  8949. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8950. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8951. }
  8952. // Local world
  8953. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8954. // Parent
  8955. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8956. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8957. } else {
  8958. this._worldMatrix.copyFrom(this._localWorld);
  8959. }
  8960. // Bounding info
  8961. this._updateBoundingInfo();
  8962. // Absolute position
  8963. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8964. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8965. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8966. }
  8967. return this._worldMatrix;
  8968. };
  8969. /**
  8970. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8971. * @param func: callback function to add
  8972. */
  8973. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8974. this._onAfterWorldMatrixUpdate.push(func);
  8975. };
  8976. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8977. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8978. if (index > -1) {
  8979. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8980. }
  8981. };
  8982. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8983. this.computeWorldMatrix();
  8984. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8985. };
  8986. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8987. this.computeWorldMatrix();
  8988. var invLocalWorldMatrix = this._localWorld.clone();
  8989. invLocalWorldMatrix.invert();
  8990. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8991. };
  8992. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8993. this.computeWorldMatrix();
  8994. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8995. };
  8996. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8997. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8998. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  8999. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9000. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9001. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9002. /// <returns>Mesh oriented towards targetMesh</returns>
  9003. yawCor = yawCor || 0; // default to zero if undefined
  9004. pitchCor = pitchCor || 0;
  9005. rollCor = rollCor || 0;
  9006. var dv = targetPoint.subtract(this.position);
  9007. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9008. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9009. var pitch = Math.atan2(dv.y, len);
  9010. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9011. };
  9012. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9013. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9014. return false;
  9015. }
  9016. return true;
  9017. };
  9018. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9019. if (!camera) {
  9020. camera = this.getScene().activeCamera;
  9021. }
  9022. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9023. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9024. return false;
  9025. }
  9026. return true;
  9027. };
  9028. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9029. if (!this._boundingInfo || !mesh._boundingInfo) {
  9030. return false;
  9031. }
  9032. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9033. };
  9034. AbstractMesh.prototype.intersectsPoint = function (point) {
  9035. if (!this._boundingInfo) {
  9036. return false;
  9037. }
  9038. return this._boundingInfo.intersectsPoint(point);
  9039. };
  9040. // Physics
  9041. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9042. var physicsEngine = this.getScene().getPhysicsEngine();
  9043. if (!physicsEngine) {
  9044. return;
  9045. }
  9046. if (impostor.impostor) {
  9047. // Old API
  9048. options = impostor;
  9049. impostor = impostor.impostor;
  9050. }
  9051. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9052. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9053. physicsEngine._unregisterMesh(this);
  9054. return;
  9055. }
  9056. options.mass = options.mass || 0;
  9057. options.friction = options.friction || 0.2;
  9058. options.restitution = options.restitution || 0.2;
  9059. this._physicImpostor = impostor;
  9060. this._physicsMass = options.mass;
  9061. this._physicsFriction = options.friction;
  9062. this._physicRestitution = options.restitution;
  9063. return physicsEngine._registerMesh(this, impostor, options);
  9064. };
  9065. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9066. if (!this._physicImpostor) {
  9067. return BABYLON.PhysicsEngine.NoImpostor;
  9068. }
  9069. return this._physicImpostor;
  9070. };
  9071. AbstractMesh.prototype.getPhysicsMass = function () {
  9072. if (!this._physicsMass) {
  9073. return 0;
  9074. }
  9075. return this._physicsMass;
  9076. };
  9077. AbstractMesh.prototype.getPhysicsFriction = function () {
  9078. if (!this._physicsFriction) {
  9079. return 0;
  9080. }
  9081. return this._physicsFriction;
  9082. };
  9083. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9084. if (!this._physicRestitution) {
  9085. return 0;
  9086. }
  9087. return this._physicRestitution;
  9088. };
  9089. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9090. if (!camera) {
  9091. camera = this.getScene().activeCamera;
  9092. }
  9093. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9094. };
  9095. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9096. if (!camera) {
  9097. camera = this.getScene().activeCamera;
  9098. }
  9099. return this.absolutePosition.subtract(camera.position).length();
  9100. };
  9101. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9102. if (!this._physicImpostor) {
  9103. return;
  9104. }
  9105. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9106. };
  9107. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9108. if (!this._physicImpostor) {
  9109. return;
  9110. }
  9111. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9112. };
  9113. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9114. if (!this._physicImpostor) {
  9115. return;
  9116. }
  9117. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9118. };
  9119. // Collisions
  9120. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9121. var globalPosition = this.getAbsolutePosition();
  9122. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9123. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9124. this._collider.radius = this.ellipsoid;
  9125. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9126. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9127. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9128. this.position.addInPlace(this._diffPositionForCollisions);
  9129. }
  9130. };
  9131. // Submeshes octree
  9132. /**
  9133. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9134. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9135. */
  9136. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9137. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  9138. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  9139. if (!this._submeshesOctree) {
  9140. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9141. }
  9142. this.computeWorldMatrix(true);
  9143. // Update octree
  9144. var bbox = this.getBoundingInfo().boundingBox;
  9145. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9146. return this._submeshesOctree;
  9147. };
  9148. // Collisions
  9149. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9150. this._generatePointsArray();
  9151. // Transformation
  9152. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9153. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9154. subMesh._lastColliderWorldVertices = [];
  9155. subMesh._trianglePlanes = [];
  9156. var start = subMesh.verticesStart;
  9157. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9158. for (var i = start; i < end; i++) {
  9159. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9160. }
  9161. }
  9162. // Collide
  9163. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9164. };
  9165. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9166. var subMeshes;
  9167. var len;
  9168. // Octrees
  9169. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9170. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9171. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9172. len = intersections.length;
  9173. subMeshes = intersections.data;
  9174. } else {
  9175. subMeshes = this.subMeshes;
  9176. len = subMeshes.length;
  9177. }
  9178. for (var index = 0; index < len; index++) {
  9179. var subMesh = subMeshes[index];
  9180. // Bounding test
  9181. if (len > 1 && !subMesh._checkCollision(collider))
  9182. continue;
  9183. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9184. }
  9185. };
  9186. AbstractMesh.prototype._checkCollision = function (collider) {
  9187. // Bounding box test
  9188. if (!this._boundingInfo._checkCollision(collider))
  9189. return;
  9190. // Transformation matrix
  9191. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9192. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9193. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9194. };
  9195. // Picking
  9196. AbstractMesh.prototype._generatePointsArray = function () {
  9197. return false;
  9198. };
  9199. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9200. var pickingInfo = new BABYLON.PickingInfo();
  9201. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9202. return pickingInfo;
  9203. }
  9204. if (!this._generatePointsArray()) {
  9205. return pickingInfo;
  9206. }
  9207. var intersectInfo = null;
  9208. // Octrees
  9209. var subMeshes;
  9210. var len;
  9211. if (this._submeshesOctree && this.useOctreeForPicking) {
  9212. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9213. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9214. len = intersections.length;
  9215. subMeshes = intersections.data;
  9216. } else {
  9217. subMeshes = this.subMeshes;
  9218. len = subMeshes.length;
  9219. }
  9220. for (var index = 0; index < len; index++) {
  9221. var subMesh = subMeshes[index];
  9222. // Bounding test
  9223. if (len > 1 && !subMesh.canIntersects(ray))
  9224. continue;
  9225. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9226. if (currentIntersectInfo) {
  9227. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9228. intersectInfo = currentIntersectInfo;
  9229. if (fastCheck) {
  9230. break;
  9231. }
  9232. }
  9233. }
  9234. }
  9235. if (intersectInfo) {
  9236. // Get picked point
  9237. var world = this.getWorldMatrix();
  9238. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9239. var direction = ray.direction.clone();
  9240. direction.normalize();
  9241. direction = direction.scale(intersectInfo.distance);
  9242. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9243. var pickedPoint = worldOrigin.add(worldDirection);
  9244. // Return result
  9245. pickingInfo.hit = true;
  9246. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9247. pickingInfo.pickedPoint = pickedPoint;
  9248. pickingInfo.pickedMesh = this;
  9249. pickingInfo.bu = intersectInfo.bu;
  9250. pickingInfo.bv = intersectInfo.bv;
  9251. pickingInfo.faceId = intersectInfo.faceId;
  9252. return pickingInfo;
  9253. }
  9254. return pickingInfo;
  9255. };
  9256. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9257. return null;
  9258. };
  9259. AbstractMesh.prototype.releaseSubMeshes = function () {
  9260. if (this.subMeshes) {
  9261. while (this.subMeshes.length) {
  9262. this.subMeshes[0].dispose();
  9263. }
  9264. } else {
  9265. this.subMeshes = new Array();
  9266. }
  9267. };
  9268. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9269. // Physics
  9270. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9271. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9272. }
  9273. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9274. var other = this._intersectionsInProgress[index];
  9275. var pos = other._intersectionsInProgress.indexOf(this);
  9276. other._intersectionsInProgress.splice(pos, 1);
  9277. }
  9278. this._intersectionsInProgress = [];
  9279. // SubMeshes
  9280. this.releaseSubMeshes();
  9281. // Remove from scene
  9282. var index = this.getScene().meshes.indexOf(this);
  9283. if (index != -1) {
  9284. // Remove from the scene if mesh found
  9285. this.getScene().meshes.splice(index, 1);
  9286. }
  9287. if (!doNotRecurse) {
  9288. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9289. if (this.getScene().particleSystems[index].emitter == this) {
  9290. this.getScene().particleSystems[index].dispose();
  9291. index--;
  9292. }
  9293. }
  9294. // Children
  9295. var objects = this.getScene().meshes.slice(0);
  9296. for (index = 0; index < objects.length; index++) {
  9297. if (objects[index].parent == this) {
  9298. objects[index].dispose();
  9299. }
  9300. }
  9301. } else {
  9302. for (index = 0; index < this.getScene().meshes.length; index++) {
  9303. var obj = this.getScene().meshes[index];
  9304. if (obj.parent === this) {
  9305. obj.parent = null;
  9306. obj.computeWorldMatrix(true);
  9307. }
  9308. }
  9309. }
  9310. this._onAfterWorldMatrixUpdate = [];
  9311. this._isDisposed = true;
  9312. // Callback
  9313. if (this.onDispose) {
  9314. this.onDispose();
  9315. }
  9316. };
  9317. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9318. AbstractMesh._BILLBOARDMODE_X = 1;
  9319. AbstractMesh._BILLBOARDMODE_Y = 2;
  9320. AbstractMesh._BILLBOARDMODE_Z = 4;
  9321. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9322. return AbstractMesh;
  9323. })(BABYLON.Node);
  9324. BABYLON.AbstractMesh = AbstractMesh;
  9325. })(BABYLON || (BABYLON = {}));
  9326. //# sourceMappingURL=babylon.abstractMesh.js.map
  9327. var BABYLON;
  9328. (function (BABYLON) {
  9329. var _InstancesBatch = (function () {
  9330. function _InstancesBatch() {
  9331. this.mustReturn = false;
  9332. this.visibleInstances = new Array();
  9333. this.renderSelf = new Array();
  9334. }
  9335. return _InstancesBatch;
  9336. })();
  9337. BABYLON._InstancesBatch = _InstancesBatch;
  9338. var Mesh = (function (_super) {
  9339. __extends(Mesh, _super);
  9340. /**
  9341. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9342. * @param {Scene} scene - The scene to add this mesh to.
  9343. * @param {Node} parent - The parent of this mesh, if it has one
  9344. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9345. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9346. * When false, achieved by calling a clone(), also passing False.
  9347. * This will make creation of children, recursive.
  9348. */
  9349. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9350. if (typeof parent === "undefined") { parent = null; }
  9351. _super.call(this, name, scene);
  9352. // Members
  9353. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9354. this.instances = new Array();
  9355. this._LODLevels = new Array();
  9356. this._onBeforeRenderCallbacks = new Array();
  9357. this._onAfterRenderCallbacks = new Array();
  9358. this._visibleInstances = {};
  9359. this._renderIdForInstances = new Array();
  9360. this._batchCache = new _InstancesBatch();
  9361. this._instancesBufferSize = 32 * 16 * 4;
  9362. if (source) {
  9363. // Geometry
  9364. if (source._geometry) {
  9365. source._geometry.applyToMesh(this);
  9366. }
  9367. // Deep copy
  9368. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9369. // Material
  9370. this.material = source.material;
  9371. if (!doNotCloneChildren) {
  9372. for (var index = 0; index < scene.meshes.length; index++) {
  9373. var mesh = scene.meshes[index];
  9374. if (mesh.parent === source) {
  9375. // doNotCloneChildren is always going to be False
  9376. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9377. }
  9378. }
  9379. }
  9380. for (index = 0; index < scene.particleSystems.length; index++) {
  9381. var system = scene.particleSystems[index];
  9382. if (system.emitter === source) {
  9383. system.clone(system.name, this);
  9384. }
  9385. }
  9386. this.computeWorldMatrix(true);
  9387. }
  9388. // Parent
  9389. if (parent !== null) {
  9390. this.parent = parent;
  9391. }
  9392. }
  9393. Mesh.prototype._clone = function () {
  9394. };
  9395. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9396. // Methods
  9397. get: function () {
  9398. return this._LODLevels.length > 0;
  9399. },
  9400. enumerable: true,
  9401. configurable: true
  9402. });
  9403. Mesh.prototype._sortLODLevels = function () {
  9404. this._LODLevels.sort(function (a, b) {
  9405. if (a.distance < b.distance) {
  9406. return 1;
  9407. }
  9408. if (a.distance > b.distance) {
  9409. return -1;
  9410. }
  9411. return 0;
  9412. });
  9413. };
  9414. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9415. if (mesh && mesh._masterMesh) {
  9416. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9417. return this;
  9418. }
  9419. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9420. this._LODLevels.push(level);
  9421. if (mesh) {
  9422. mesh._masterMesh = this;
  9423. }
  9424. this._sortLODLevels();
  9425. return this;
  9426. };
  9427. Mesh.prototype.removeLODLevel = function (mesh) {
  9428. for (var index = 0; index < this._LODLevels.length; index++) {
  9429. if (this._LODLevels[index].mesh === mesh) {
  9430. this._LODLevels.splice(index, 1);
  9431. if (mesh) {
  9432. mesh._masterMesh = null;
  9433. }
  9434. }
  9435. }
  9436. this._sortLODLevels();
  9437. return this;
  9438. };
  9439. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9440. if (!this._LODLevels || this._LODLevels.length === 0) {
  9441. return this;
  9442. }
  9443. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9444. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9445. return this;
  9446. }
  9447. for (var index = 0; index < this._LODLevels.length; index++) {
  9448. var level = this._LODLevels[index];
  9449. if (level.distance < distanceToCamera) {
  9450. if (level.mesh) {
  9451. level.mesh._preActivate();
  9452. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9453. }
  9454. return level.mesh;
  9455. }
  9456. }
  9457. return this;
  9458. };
  9459. Object.defineProperty(Mesh.prototype, "geometry", {
  9460. get: function () {
  9461. return this._geometry;
  9462. },
  9463. enumerable: true,
  9464. configurable: true
  9465. });
  9466. Mesh.prototype.getTotalVertices = function () {
  9467. if (!this._geometry) {
  9468. return 0;
  9469. }
  9470. return this._geometry.getTotalVertices();
  9471. };
  9472. Mesh.prototype.getVerticesData = function (kind) {
  9473. if (!this._geometry) {
  9474. return null;
  9475. }
  9476. return this._geometry.getVerticesData(kind);
  9477. };
  9478. Mesh.prototype.getVertexBuffer = function (kind) {
  9479. if (!this._geometry) {
  9480. return undefined;
  9481. }
  9482. return this._geometry.getVertexBuffer(kind);
  9483. };
  9484. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9485. if (!this._geometry) {
  9486. if (this._delayInfo) {
  9487. return this._delayInfo.indexOf(kind) !== -1;
  9488. }
  9489. return false;
  9490. }
  9491. return this._geometry.isVerticesDataPresent(kind);
  9492. };
  9493. Mesh.prototype.getVerticesDataKinds = function () {
  9494. if (!this._geometry) {
  9495. var result = [];
  9496. if (this._delayInfo) {
  9497. for (var kind in this._delayInfo) {
  9498. result.push(kind);
  9499. }
  9500. }
  9501. return result;
  9502. }
  9503. return this._geometry.getVerticesDataKinds();
  9504. };
  9505. Mesh.prototype.getTotalIndices = function () {
  9506. if (!this._geometry) {
  9507. return 0;
  9508. }
  9509. return this._geometry.getTotalIndices();
  9510. };
  9511. Mesh.prototype.getIndices = function () {
  9512. if (!this._geometry) {
  9513. return [];
  9514. }
  9515. return this._geometry.getIndices();
  9516. };
  9517. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9518. get: function () {
  9519. return this._masterMesh !== null && this._masterMesh !== undefined;
  9520. },
  9521. enumerable: true,
  9522. configurable: true
  9523. });
  9524. Mesh.prototype.isReady = function () {
  9525. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9526. return false;
  9527. }
  9528. return _super.prototype.isReady.call(this);
  9529. };
  9530. Mesh.prototype.isDisposed = function () {
  9531. return this._isDisposed;
  9532. };
  9533. // Methods
  9534. Mesh.prototype._preActivate = function () {
  9535. var sceneRenderId = this.getScene().getRenderId();
  9536. if (this._preActivateId == sceneRenderId) {
  9537. return;
  9538. }
  9539. this._preActivateId = sceneRenderId;
  9540. this._visibleInstances = null;
  9541. };
  9542. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9543. if (!this._visibleInstances) {
  9544. this._visibleInstances = {};
  9545. this._visibleInstances.defaultRenderId = renderId;
  9546. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9547. }
  9548. if (!this._visibleInstances[renderId]) {
  9549. this._visibleInstances[renderId] = new Array();
  9550. }
  9551. this._visibleInstances[renderId].push(instance);
  9552. };
  9553. Mesh.prototype.refreshBoundingInfo = function () {
  9554. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9555. if (data) {
  9556. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9557. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9558. }
  9559. if (this.subMeshes) {
  9560. for (var index = 0; index < this.subMeshes.length; index++) {
  9561. this.subMeshes[index].refreshBoundingInfo();
  9562. }
  9563. }
  9564. this._updateBoundingInfo();
  9565. };
  9566. Mesh.prototype._createGlobalSubMesh = function () {
  9567. var totalVertices = this.getTotalVertices();
  9568. if (!totalVertices || !this.getIndices()) {
  9569. return null;
  9570. }
  9571. this.releaseSubMeshes();
  9572. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9573. };
  9574. Mesh.prototype.subdivide = function (count) {
  9575. if (count < 1) {
  9576. return;
  9577. }
  9578. var totalIndices = this.getTotalIndices();
  9579. var subdivisionSize = (totalIndices / count) | 0;
  9580. var offset = 0;
  9581. while (subdivisionSize % 3 != 0) {
  9582. subdivisionSize++;
  9583. }
  9584. this.releaseSubMeshes();
  9585. for (var index = 0; index < count; index++) {
  9586. if (offset >= totalIndices) {
  9587. break;
  9588. }
  9589. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9590. offset += subdivisionSize;
  9591. }
  9592. this.synchronizeInstances();
  9593. };
  9594. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  9595. if (kind instanceof Array) {
  9596. var temp = data;
  9597. data = kind;
  9598. kind = temp;
  9599. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9600. }
  9601. if (!this._geometry) {
  9602. var vertexData = new BABYLON.VertexData();
  9603. vertexData.set(data, kind);
  9604. var scene = this.getScene();
  9605. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9606. } else {
  9607. this._geometry.setVerticesData(kind, data, updatable, stride);
  9608. }
  9609. };
  9610. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9611. if (!this._geometry) {
  9612. return;
  9613. }
  9614. if (!makeItUnique) {
  9615. this._geometry.updateVerticesData(kind, data, updateExtends);
  9616. } else {
  9617. this.makeGeometryUnique();
  9618. this.updateVerticesData(kind, data, updateExtends, false);
  9619. }
  9620. };
  9621. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  9622. if (!this._geometry) {
  9623. return;
  9624. }
  9625. if (!makeItUnique) {
  9626. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  9627. } else {
  9628. this.makeGeometryUnique();
  9629. this.updateVerticesDataDirectly(kind, data, offset, false);
  9630. }
  9631. };
  9632. Mesh.prototype.makeGeometryUnique = function () {
  9633. if (!this._geometry) {
  9634. return;
  9635. }
  9636. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9637. geometry.applyToMesh(this);
  9638. };
  9639. Mesh.prototype.setIndices = function (indices, totalVertices) {
  9640. if (!this._geometry) {
  9641. var vertexData = new BABYLON.VertexData();
  9642. vertexData.indices = indices;
  9643. var scene = this.getScene();
  9644. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9645. } else {
  9646. this._geometry.setIndices(indices, totalVertices);
  9647. }
  9648. };
  9649. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  9650. var engine = this.getScene().getEngine();
  9651. // Wireframe
  9652. var indexToBind;
  9653. switch (fillMode) {
  9654. case BABYLON.Material.PointFillMode:
  9655. indexToBind = null;
  9656. break;
  9657. case BABYLON.Material.WireFrameFillMode:
  9658. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  9659. break;
  9660. default:
  9661. case BABYLON.Material.TriangleFillMode:
  9662. indexToBind = this._geometry.getIndexBuffer();
  9663. break;
  9664. }
  9665. // VBOs
  9666. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  9667. };
  9668. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  9669. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9670. return;
  9671. }
  9672. var engine = this.getScene().getEngine();
  9673. switch (fillMode) {
  9674. case BABYLON.Material.PointFillMode:
  9675. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  9676. break;
  9677. case BABYLON.Material.WireFrameFillMode:
  9678. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  9679. break;
  9680. default:
  9681. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  9682. }
  9683. };
  9684. Mesh.prototype.registerBeforeRender = function (func) {
  9685. this._onBeforeRenderCallbacks.push(func);
  9686. };
  9687. Mesh.prototype.unregisterBeforeRender = function (func) {
  9688. var index = this._onBeforeRenderCallbacks.indexOf(func);
  9689. if (index > -1) {
  9690. this._onBeforeRenderCallbacks.splice(index, 1);
  9691. }
  9692. };
  9693. Mesh.prototype.registerAfterRender = function (func) {
  9694. this._onAfterRenderCallbacks.push(func);
  9695. };
  9696. Mesh.prototype.unregisterAfterRender = function (func) {
  9697. var index = this._onAfterRenderCallbacks.indexOf(func);
  9698. if (index > -1) {
  9699. this._onAfterRenderCallbacks.splice(index, 1);
  9700. }
  9701. };
  9702. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  9703. var scene = this.getScene();
  9704. this._batchCache.mustReturn = false;
  9705. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  9706. this._batchCache.visibleInstances[subMeshId] = null;
  9707. if (this._visibleInstances) {
  9708. var currentRenderId = scene.getRenderId();
  9709. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  9710. var selfRenderId = this._renderId;
  9711. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  9712. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  9713. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  9714. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  9715. }
  9716. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  9717. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  9718. this._batchCache.mustReturn = true;
  9719. return this._batchCache;
  9720. }
  9721. if (currentRenderId !== selfRenderId) {
  9722. this._batchCache.renderSelf[subMeshId] = false;
  9723. }
  9724. }
  9725. this._renderIdForInstances[subMeshId] = currentRenderId;
  9726. }
  9727. return this._batchCache;
  9728. };
  9729. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  9730. var visibleInstances = batch.visibleInstances[subMesh._id];
  9731. var matricesCount = visibleInstances.length + 1;
  9732. var bufferSize = matricesCount * 16 * 4;
  9733. while (this._instancesBufferSize < bufferSize) {
  9734. this._instancesBufferSize *= 2;
  9735. }
  9736. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  9737. if (this._worldMatricesInstancesBuffer) {
  9738. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9739. }
  9740. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  9741. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  9742. }
  9743. var offset = 0;
  9744. var instancesCount = 0;
  9745. var world = this.getWorldMatrix();
  9746. if (batch.renderSelf[subMesh._id]) {
  9747. world.copyToArray(this._worldMatricesInstancesArray, offset);
  9748. offset += 16;
  9749. instancesCount++;
  9750. }
  9751. if (visibleInstances) {
  9752. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  9753. var instance = visibleInstances[instanceIndex];
  9754. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  9755. offset += 16;
  9756. instancesCount++;
  9757. }
  9758. }
  9759. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  9760. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  9761. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  9762. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  9763. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  9764. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  9765. this._draw(subMesh, fillMode, instancesCount);
  9766. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  9767. };
  9768. Mesh.prototype.render = function (subMesh) {
  9769. var scene = this.getScene();
  9770. // Managing instances
  9771. var batch = this._getInstancesRenderList(subMesh._id);
  9772. if (batch.mustReturn) {
  9773. return;
  9774. }
  9775. // Checking geometry state
  9776. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9777. return;
  9778. }
  9779. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9780. this._onBeforeRenderCallbacks[callbackIndex]();
  9781. }
  9782. var engine = scene.getEngine();
  9783. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9784. // Material
  9785. var effectiveMaterial = subMesh.getMaterial();
  9786. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  9787. return;
  9788. }
  9789. // Outline - step 1
  9790. var savedDepthWrite = engine.getDepthWrite();
  9791. if (this.renderOutline) {
  9792. engine.setDepthWrite(false);
  9793. scene.getOutlineRenderer().render(subMesh, batch);
  9794. engine.setDepthWrite(savedDepthWrite);
  9795. }
  9796. effectiveMaterial._preBind();
  9797. var effect = effectiveMaterial.getEffect();
  9798. // Bind
  9799. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  9800. this._bind(subMesh, effect, fillMode);
  9801. var world = this.getWorldMatrix();
  9802. effectiveMaterial.bind(world, this);
  9803. // Instances rendering
  9804. if (hardwareInstancedRendering) {
  9805. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  9806. } else {
  9807. if (batch.renderSelf[subMesh._id]) {
  9808. // Draw
  9809. this._draw(subMesh, fillMode);
  9810. }
  9811. if (batch.visibleInstances[subMesh._id]) {
  9812. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  9813. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  9814. // World
  9815. world = instance.getWorldMatrix();
  9816. effectiveMaterial.bindOnlyWorldMatrix(world);
  9817. // Draw
  9818. this._draw(subMesh, fillMode);
  9819. }
  9820. }
  9821. }
  9822. // Unbind
  9823. effectiveMaterial.unbind();
  9824. // Outline - step 2
  9825. if (this.renderOutline && savedDepthWrite) {
  9826. engine.setDepthWrite(true);
  9827. engine.setColorWrite(false);
  9828. scene.getOutlineRenderer().render(subMesh, batch);
  9829. engine.setColorWrite(true);
  9830. }
  9831. // Overlay
  9832. if (this.renderOverlay) {
  9833. var currentMode = engine.getAlphaMode();
  9834. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9835. scene.getOutlineRenderer().render(subMesh, batch, true);
  9836. engine.setAlphaMode(currentMode);
  9837. }
  9838. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9839. this._onAfterRenderCallbacks[callbackIndex]();
  9840. }
  9841. };
  9842. Mesh.prototype.getEmittedParticleSystems = function () {
  9843. var results = new Array();
  9844. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9845. var particleSystem = this.getScene().particleSystems[index];
  9846. if (particleSystem.emitter === this) {
  9847. results.push(particleSystem);
  9848. }
  9849. }
  9850. return results;
  9851. };
  9852. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  9853. var results = new Array();
  9854. var descendants = this.getDescendants();
  9855. descendants.push(this);
  9856. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9857. var particleSystem = this.getScene().particleSystems[index];
  9858. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  9859. results.push(particleSystem);
  9860. }
  9861. }
  9862. return results;
  9863. };
  9864. Mesh.prototype.getChildren = function () {
  9865. var results = [];
  9866. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9867. var mesh = this.getScene().meshes[index];
  9868. if (mesh.parent == this) {
  9869. results.push(mesh);
  9870. }
  9871. }
  9872. return results;
  9873. };
  9874. Mesh.prototype._checkDelayState = function () {
  9875. var _this = this;
  9876. var that = this;
  9877. var scene = this.getScene();
  9878. if (this._geometry) {
  9879. this._geometry.load(scene);
  9880. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9881. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  9882. scene._addPendingData(that);
  9883. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  9884. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  9885. if (data instanceof ArrayBuffer) {
  9886. _this._delayLoadingFunction(data, _this);
  9887. } else {
  9888. _this._delayLoadingFunction(JSON.parse(data), _this);
  9889. }
  9890. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9891. scene._removePendingData(_this);
  9892. }, function () {
  9893. }, scene.database, getBinaryData);
  9894. }
  9895. };
  9896. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  9897. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9898. return false;
  9899. }
  9900. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  9901. return false;
  9902. }
  9903. this._checkDelayState();
  9904. return true;
  9905. };
  9906. Mesh.prototype.setMaterialByID = function (id) {
  9907. var materials = this.getScene().materials;
  9908. for (var index = 0; index < materials.length; index++) {
  9909. if (materials[index].id == id) {
  9910. this.material = materials[index];
  9911. return;
  9912. }
  9913. }
  9914. // Multi
  9915. var multiMaterials = this.getScene().multiMaterials;
  9916. for (index = 0; index < multiMaterials.length; index++) {
  9917. if (multiMaterials[index].id == id) {
  9918. this.material = multiMaterials[index];
  9919. return;
  9920. }
  9921. }
  9922. };
  9923. Mesh.prototype.getAnimatables = function () {
  9924. var results = [];
  9925. if (this.material) {
  9926. results.push(this.material);
  9927. }
  9928. if (this.skeleton) {
  9929. results.push(this.skeleton);
  9930. }
  9931. return results;
  9932. };
  9933. // Geometry
  9934. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  9935. // Position
  9936. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  9937. return;
  9938. }
  9939. this._resetPointsArrayCache();
  9940. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9941. var temp = [];
  9942. for (var index = 0; index < data.length; index += 3) {
  9943. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9944. }
  9945. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  9946. // Normals
  9947. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9948. return;
  9949. }
  9950. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9951. for (index = 0; index < data.length; index += 3) {
  9952. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9953. }
  9954. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  9955. };
  9956. // Cache
  9957. Mesh.prototype._resetPointsArrayCache = function () {
  9958. this._positions = null;
  9959. };
  9960. Mesh.prototype._generatePointsArray = function () {
  9961. if (this._positions)
  9962. return true;
  9963. this._positions = [];
  9964. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9965. if (!data) {
  9966. return false;
  9967. }
  9968. for (var index = 0; index < data.length; index += 3) {
  9969. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  9970. }
  9971. return true;
  9972. };
  9973. // Clone
  9974. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9975. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  9976. };
  9977. // Dispose
  9978. Mesh.prototype.dispose = function (doNotRecurse) {
  9979. if (this._geometry) {
  9980. this._geometry.releaseForMesh(this, true);
  9981. }
  9982. // Instances
  9983. if (this._worldMatricesInstancesBuffer) {
  9984. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9985. this._worldMatricesInstancesBuffer = null;
  9986. }
  9987. while (this.instances.length) {
  9988. this.instances[0].dispose();
  9989. }
  9990. _super.prototype.dispose.call(this, doNotRecurse);
  9991. };
  9992. // Geometric tools
  9993. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9994. var _this = this;
  9995. var scene = this.getScene();
  9996. var onload = function (img) {
  9997. // Getting height map data
  9998. var canvas = document.createElement("canvas");
  9999. var context = canvas.getContext("2d");
  10000. var heightMapWidth = img.width;
  10001. var heightMapHeight = img.height;
  10002. canvas.width = heightMapWidth;
  10003. canvas.height = heightMapHeight;
  10004. context.drawImage(img, 0, 0);
  10005. // Create VertexData from map data
  10006. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10007. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10008. };
  10009. BABYLON.Tools.LoadImage(url, onload, function () {
  10010. }, scene.database);
  10011. };
  10012. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10013. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10014. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10015. return;
  10016. }
  10017. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10018. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10019. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10020. var position = BABYLON.Vector3.Zero();
  10021. var normal = BABYLON.Vector3.Zero();
  10022. var uv = BABYLON.Vector2.Zero();
  10023. for (var index = 0; index < positions.length; index += 3) {
  10024. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10025. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10026. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10027. // Compute height
  10028. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10029. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10030. var pos = (u + v * heightMapWidth) * 4;
  10031. var r = buffer[pos] / 255.0;
  10032. var g = buffer[pos + 1] / 255.0;
  10033. var b = buffer[pos + 2] / 255.0;
  10034. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10035. normal.normalize();
  10036. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10037. position = position.add(normal);
  10038. position.toArray(positions, index);
  10039. }
  10040. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10041. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10042. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10043. };
  10044. Mesh.prototype.convertToFlatShadedMesh = function () {
  10045. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10046. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10047. var kinds = this.getVerticesDataKinds();
  10048. var vbs = [];
  10049. var data = [];
  10050. var newdata = [];
  10051. var updatableNormals = false;
  10052. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10053. var kind = kinds[kindIndex];
  10054. var vertexBuffer = this.getVertexBuffer(kind);
  10055. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10056. updatableNormals = vertexBuffer.isUpdatable();
  10057. kinds.splice(kindIndex, 1);
  10058. kindIndex--;
  10059. continue;
  10060. }
  10061. vbs[kind] = vertexBuffer;
  10062. data[kind] = vbs[kind].getData();
  10063. newdata[kind] = [];
  10064. }
  10065. // Save previous submeshes
  10066. var previousSubmeshes = this.subMeshes.slice(0);
  10067. var indices = this.getIndices();
  10068. var totalIndices = this.getTotalIndices();
  10069. for (var index = 0; index < totalIndices; index++) {
  10070. var vertexIndex = indices[index];
  10071. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10072. kind = kinds[kindIndex];
  10073. var stride = vbs[kind].getStrideSize();
  10074. for (var offset = 0; offset < stride; offset++) {
  10075. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10076. }
  10077. }
  10078. }
  10079. // Updating faces & normal
  10080. var normals = [];
  10081. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10082. for (index = 0; index < totalIndices; index += 3) {
  10083. indices[index] = index;
  10084. indices[index + 1] = index + 1;
  10085. indices[index + 2] = index + 2;
  10086. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10087. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10088. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10089. var p1p2 = p1.subtract(p2);
  10090. var p3p2 = p3.subtract(p2);
  10091. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10092. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10093. normals.push(normal.x);
  10094. normals.push(normal.y);
  10095. normals.push(normal.z);
  10096. }
  10097. }
  10098. this.setIndices(indices);
  10099. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10100. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10101. kind = kinds[kindIndex];
  10102. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10103. }
  10104. // Updating submeshes
  10105. this.releaseSubMeshes();
  10106. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10107. var previousOne = previousSubmeshes[submeshIndex];
  10108. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10109. }
  10110. this.synchronizeInstances();
  10111. };
  10112. // Instances
  10113. Mesh.prototype.createInstance = function (name) {
  10114. return new BABYLON.InstancedMesh(name, this);
  10115. };
  10116. Mesh.prototype.synchronizeInstances = function () {
  10117. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10118. var instance = this.instances[instanceIndex];
  10119. instance._syncSubMeshes();
  10120. }
  10121. };
  10122. /**
  10123. * Simplify the mesh according to the given array of settings.
  10124. * Function will return immediately and will simplify async.
  10125. * @param settings a collection of simplification settings.
  10126. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10127. * @param type the type of simplification to run.
  10128. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10129. */
  10130. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10131. var _this = this;
  10132. if (typeof parallelProcessing === "undefined") { parallelProcessing = true; }
  10133. if (typeof type === "undefined") { type = 0 /* QUADRATIC */; }
  10134. var getSimplifier = function () {
  10135. switch (type) {
  10136. case 0 /* QUADRATIC */:
  10137. default:
  10138. return new BABYLON.QuadraticErrorSimplification(_this);
  10139. }
  10140. };
  10141. if (parallelProcessing) {
  10142. //parallel simplifier
  10143. settings.forEach(function (setting) {
  10144. var simplifier = getSimplifier();
  10145. simplifier.simplify(setting, function (newMesh) {
  10146. _this.addLODLevel(setting.distance, newMesh);
  10147. //check if it is the last
  10148. if (setting.quality == settings[settings.length - 1].quality && successCallback) {
  10149. //all done, run the success callback.
  10150. successCallback();
  10151. }
  10152. });
  10153. });
  10154. } else {
  10155. //single simplifier.
  10156. var simplifier = getSimplifier();
  10157. var runDecimation = function (setting, callback) {
  10158. simplifier.simplify(setting, function (newMesh) {
  10159. _this.addLODLevel(setting.distance, newMesh);
  10160. //run the next quality level
  10161. callback();
  10162. });
  10163. };
  10164. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10165. runDecimation(settings[loop.index], function () {
  10166. loop.executeNext();
  10167. });
  10168. }, function () {
  10169. //execution ended, run the success callback.
  10170. if (successCallback) {
  10171. successCallback();
  10172. }
  10173. });
  10174. }
  10175. };
  10176. // Statics
  10177. Mesh.CreateBox = function (name, size, scene, updatable) {
  10178. var box = new Mesh(name, scene);
  10179. var vertexData = BABYLON.VertexData.CreateBox(size);
  10180. vertexData.applyToMesh(box, updatable);
  10181. return box;
  10182. };
  10183. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10184. var sphere = new Mesh(name, scene);
  10185. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10186. vertexData.applyToMesh(sphere, updatable);
  10187. return sphere;
  10188. };
  10189. // Cylinder and cone (Code inspired by SharpDX.org)
  10190. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10191. // subdivisions is a new parameter, we need to support old signature
  10192. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10193. if (scene !== undefined) {
  10194. updatable = scene;
  10195. }
  10196. scene = subdivisions;
  10197. subdivisions = 1;
  10198. }
  10199. var cylinder = new Mesh(name, scene);
  10200. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10201. vertexData.applyToMesh(cylinder, updatable);
  10202. return cylinder;
  10203. };
  10204. // Torus (Code from SharpDX.org)
  10205. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10206. var torus = new Mesh(name, scene);
  10207. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10208. vertexData.applyToMesh(torus, updatable);
  10209. return torus;
  10210. };
  10211. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10212. var torusKnot = new Mesh(name, scene);
  10213. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10214. vertexData.applyToMesh(torusKnot, updatable);
  10215. return torusKnot;
  10216. };
  10217. // Lines
  10218. Mesh.CreateLines = function (name, points, scene, updatable) {
  10219. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10220. var vertexData = BABYLON.VertexData.CreateLines(points);
  10221. vertexData.applyToMesh(lines, updatable);
  10222. return lines;
  10223. };
  10224. // Plane & ground
  10225. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10226. var plane = new Mesh(name, scene);
  10227. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10228. vertexData.applyToMesh(plane, updatable);
  10229. return plane;
  10230. };
  10231. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10232. var ground = new BABYLON.GroundMesh(name, scene);
  10233. ground._setReady(false);
  10234. ground._subdivisions = subdivisions;
  10235. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10236. vertexData.applyToMesh(ground, updatable);
  10237. ground._setReady(true);
  10238. return ground;
  10239. };
  10240. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10241. var tiledGround = new Mesh(name, scene);
  10242. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10243. vertexData.applyToMesh(tiledGround, updatable);
  10244. return tiledGround;
  10245. };
  10246. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  10247. var ground = new BABYLON.GroundMesh(name, scene);
  10248. ground._subdivisions = subdivisions;
  10249. ground._setReady(false);
  10250. var onload = function (img) {
  10251. // Getting height map data
  10252. var canvas = document.createElement("canvas");
  10253. var context = canvas.getContext("2d");
  10254. var heightMapWidth = img.width;
  10255. var heightMapHeight = img.height;
  10256. canvas.width = heightMapWidth;
  10257. canvas.height = heightMapHeight;
  10258. context.drawImage(img, 0, 0);
  10259. // Create VertexData from map data
  10260. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10261. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10262. vertexData.applyToMesh(ground, updatable);
  10263. ground._setReady(true);
  10264. };
  10265. BABYLON.Tools.LoadImage(url, onload, function () {
  10266. }, scene.database);
  10267. return ground;
  10268. };
  10269. // Tools
  10270. Mesh.MinMax = function (meshes) {
  10271. var minVector = null;
  10272. var maxVector = null;
  10273. for (var i in meshes) {
  10274. var mesh = meshes[i];
  10275. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10276. if (!minVector) {
  10277. minVector = boundingBox.minimumWorld;
  10278. maxVector = boundingBox.maximumWorld;
  10279. continue;
  10280. }
  10281. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10282. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10283. }
  10284. return {
  10285. min: minVector,
  10286. max: maxVector
  10287. };
  10288. };
  10289. Mesh.Center = function (meshesOrMinMaxVector) {
  10290. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  10291. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10292. };
  10293. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10294. if (typeof disposeSource === "undefined") { disposeSource = true; }
  10295. var source = meshes[0];
  10296. var material = source.material;
  10297. var scene = source.getScene();
  10298. if (!allow32BitsIndices) {
  10299. var totalVertices = 0;
  10300. for (var index = 0; index < meshes.length; index++) {
  10301. totalVertices += meshes[index].getTotalVertices();
  10302. if (totalVertices > 65536) {
  10303. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10304. return null;
  10305. }
  10306. }
  10307. }
  10308. // Merge
  10309. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10310. vertexData.transform(source.getWorldMatrix());
  10311. for (index = 1; index < meshes.length; index++) {
  10312. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10313. otherVertexData.transform(meshes[index].getWorldMatrix());
  10314. vertexData.merge(otherVertexData);
  10315. }
  10316. var newMesh = new Mesh(source.name + "_merged", scene);
  10317. vertexData.applyToMesh(newMesh);
  10318. // Setting properties
  10319. newMesh.material = material;
  10320. newMesh.checkCollisions = source.checkCollisions;
  10321. // Cleaning
  10322. if (disposeSource) {
  10323. for (index = 0; index < meshes.length; index++) {
  10324. meshes[index].dispose();
  10325. }
  10326. }
  10327. return newMesh;
  10328. };
  10329. return Mesh;
  10330. })(BABYLON.AbstractMesh);
  10331. BABYLON.Mesh = Mesh;
  10332. })(BABYLON || (BABYLON = {}));
  10333. //# sourceMappingURL=babylon.mesh.js.map
  10334. var BABYLON;
  10335. (function (BABYLON) {
  10336. var GroundMesh = (function (_super) {
  10337. __extends(GroundMesh, _super);
  10338. function GroundMesh(name, scene) {
  10339. _super.call(this, name, scene);
  10340. this.generateOctree = false;
  10341. this._worldInverse = new BABYLON.Matrix();
  10342. }
  10343. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10344. get: function () {
  10345. return this._subdivisions;
  10346. },
  10347. enumerable: true,
  10348. configurable: true
  10349. });
  10350. GroundMesh.prototype.optimize = function (chunksCount) {
  10351. this.subdivide(this._subdivisions);
  10352. this.createOrUpdateSubmeshesOctree(32);
  10353. };
  10354. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10355. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10356. this.getWorldMatrix().invertToRef(this._worldInverse);
  10357. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10358. var pickInfo = this.intersects(ray);
  10359. if (pickInfo.hit) {
  10360. return pickInfo.pickedPoint.y;
  10361. }
  10362. return 0;
  10363. };
  10364. return GroundMesh;
  10365. })(BABYLON.Mesh);
  10366. BABYLON.GroundMesh = GroundMesh;
  10367. })(BABYLON || (BABYLON = {}));
  10368. //# sourceMappingURL=babylon.groundMesh.js.map
  10369. var BABYLON;
  10370. (function (BABYLON) {
  10371. var InstancedMesh = (function (_super) {
  10372. __extends(InstancedMesh, _super);
  10373. function InstancedMesh(name, source) {
  10374. _super.call(this, name, source.getScene());
  10375. source.instances.push(this);
  10376. this._sourceMesh = source;
  10377. this.position.copyFrom(source.position);
  10378. this.rotation.copyFrom(source.rotation);
  10379. this.scaling.copyFrom(source.scaling);
  10380. if (source.rotationQuaternion) {
  10381. this.rotationQuaternion = source.rotationQuaternion.clone();
  10382. }
  10383. this.infiniteDistance = source.infiniteDistance;
  10384. this.setPivotMatrix(source.getPivotMatrix());
  10385. this.refreshBoundingInfo();
  10386. this._syncSubMeshes();
  10387. }
  10388. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10389. // Methods
  10390. get: function () {
  10391. return this._sourceMesh.receiveShadows;
  10392. },
  10393. enumerable: true,
  10394. configurable: true
  10395. });
  10396. Object.defineProperty(InstancedMesh.prototype, "material", {
  10397. get: function () {
  10398. return this._sourceMesh.material;
  10399. },
  10400. enumerable: true,
  10401. configurable: true
  10402. });
  10403. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10404. get: function () {
  10405. return this._sourceMesh.visibility;
  10406. },
  10407. enumerable: true,
  10408. configurable: true
  10409. });
  10410. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10411. get: function () {
  10412. return this._sourceMesh.skeleton;
  10413. },
  10414. enumerable: true,
  10415. configurable: true
  10416. });
  10417. InstancedMesh.prototype.getTotalVertices = function () {
  10418. return this._sourceMesh.getTotalVertices();
  10419. };
  10420. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10421. get: function () {
  10422. return this._sourceMesh;
  10423. },
  10424. enumerable: true,
  10425. configurable: true
  10426. });
  10427. InstancedMesh.prototype.getVerticesData = function (kind) {
  10428. return this._sourceMesh.getVerticesData(kind);
  10429. };
  10430. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10431. return this._sourceMesh.isVerticesDataPresent(kind);
  10432. };
  10433. InstancedMesh.prototype.getIndices = function () {
  10434. return this._sourceMesh.getIndices();
  10435. };
  10436. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10437. get: function () {
  10438. return this._sourceMesh._positions;
  10439. },
  10440. enumerable: true,
  10441. configurable: true
  10442. });
  10443. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10444. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10445. if (data) {
  10446. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10447. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10448. }
  10449. this._updateBoundingInfo();
  10450. };
  10451. InstancedMesh.prototype._preActivate = function () {
  10452. if (this._currentLOD) {
  10453. this._currentLOD._preActivate();
  10454. }
  10455. };
  10456. InstancedMesh.prototype._activate = function (renderId) {
  10457. if (this._currentLOD) {
  10458. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10459. }
  10460. };
  10461. InstancedMesh.prototype.getLOD = function (camera) {
  10462. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10463. if (this._currentLOD === this.sourceMesh) {
  10464. return this;
  10465. }
  10466. return this._currentLOD;
  10467. };
  10468. InstancedMesh.prototype._syncSubMeshes = function () {
  10469. this.releaseSubMeshes();
  10470. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10471. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10472. }
  10473. };
  10474. InstancedMesh.prototype._generatePointsArray = function () {
  10475. return this._sourceMesh._generatePointsArray();
  10476. };
  10477. // Clone
  10478. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10479. var result = this._sourceMesh.createInstance(name);
  10480. // Deep copy
  10481. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10482. // Bounding info
  10483. this.refreshBoundingInfo();
  10484. // Parent
  10485. if (newParent) {
  10486. result.parent = newParent;
  10487. }
  10488. if (!doNotCloneChildren) {
  10489. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10490. var mesh = this.getScene().meshes[index];
  10491. if (mesh.parent == this) {
  10492. mesh.clone(mesh.name, result);
  10493. }
  10494. }
  10495. }
  10496. result.computeWorldMatrix(true);
  10497. return result;
  10498. };
  10499. // Dispoe
  10500. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10501. // Remove from mesh
  10502. var index = this._sourceMesh.instances.indexOf(this);
  10503. this._sourceMesh.instances.splice(index, 1);
  10504. _super.prototype.dispose.call(this, doNotRecurse);
  10505. };
  10506. return InstancedMesh;
  10507. })(BABYLON.AbstractMesh);
  10508. BABYLON.InstancedMesh = InstancedMesh;
  10509. })(BABYLON || (BABYLON = {}));
  10510. //# sourceMappingURL=babylon.instancedMesh.js.map
  10511. var BABYLON;
  10512. (function (BABYLON) {
  10513. var SubMesh = (function () {
  10514. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10515. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  10516. this.materialIndex = materialIndex;
  10517. this.verticesStart = verticesStart;
  10518. this.verticesCount = verticesCount;
  10519. this.indexStart = indexStart;
  10520. this.indexCount = indexCount;
  10521. this._renderId = 0;
  10522. this._mesh = mesh;
  10523. this._renderingMesh = renderingMesh || mesh;
  10524. mesh.subMeshes.push(this);
  10525. this._id = mesh.subMeshes.length - 1;
  10526. if (createBoundingBox) {
  10527. this.refreshBoundingInfo();
  10528. }
  10529. }
  10530. SubMesh.prototype.getBoundingInfo = function () {
  10531. return this._boundingInfo;
  10532. };
  10533. SubMesh.prototype.getMesh = function () {
  10534. return this._mesh;
  10535. };
  10536. SubMesh.prototype.getRenderingMesh = function () {
  10537. return this._renderingMesh;
  10538. };
  10539. SubMesh.prototype.getMaterial = function () {
  10540. var rootMaterial = this._renderingMesh.material;
  10541. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10542. var multiMaterial = rootMaterial;
  10543. return multiMaterial.getSubMaterial(this.materialIndex);
  10544. }
  10545. if (!rootMaterial) {
  10546. return this._mesh.getScene().defaultMaterial;
  10547. }
  10548. return rootMaterial;
  10549. };
  10550. // Methods
  10551. SubMesh.prototype.refreshBoundingInfo = function () {
  10552. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10553. if (!data) {
  10554. this._boundingInfo = this._mesh._boundingInfo;
  10555. return;
  10556. }
  10557. var indices = this._renderingMesh.getIndices();
  10558. var extend;
  10559. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10560. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10561. } else {
  10562. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10563. }
  10564. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10565. };
  10566. SubMesh.prototype._checkCollision = function (collider) {
  10567. return this._boundingInfo._checkCollision(collider);
  10568. };
  10569. SubMesh.prototype.updateBoundingInfo = function (world) {
  10570. if (!this._boundingInfo) {
  10571. this.refreshBoundingInfo();
  10572. }
  10573. this._boundingInfo._update(world);
  10574. };
  10575. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10576. return this._boundingInfo.isInFrustum(frustumPlanes);
  10577. };
  10578. SubMesh.prototype.render = function () {
  10579. this._renderingMesh.render(this);
  10580. };
  10581. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10582. if (!this._linesIndexBuffer) {
  10583. var linesIndices = [];
  10584. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10585. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10586. }
  10587. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10588. this.linesIndexCount = linesIndices.length;
  10589. }
  10590. return this._linesIndexBuffer;
  10591. };
  10592. SubMesh.prototype.canIntersects = function (ray) {
  10593. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10594. };
  10595. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10596. var intersectInfo = null;
  10597. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10598. var p0 = positions[indices[index]];
  10599. var p1 = positions[indices[index + 1]];
  10600. var p2 = positions[indices[index + 2]];
  10601. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10602. if (currentIntersectInfo) {
  10603. if (currentIntersectInfo.distance < 0) {
  10604. continue;
  10605. }
  10606. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10607. intersectInfo = currentIntersectInfo;
  10608. intersectInfo.faceId = index / 3;
  10609. if (fastCheck) {
  10610. break;
  10611. }
  10612. }
  10613. }
  10614. }
  10615. return intersectInfo;
  10616. };
  10617. // Clone
  10618. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10619. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10620. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10621. return result;
  10622. };
  10623. // Dispose
  10624. SubMesh.prototype.dispose = function () {
  10625. if (this._linesIndexBuffer) {
  10626. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10627. this._linesIndexBuffer = null;
  10628. }
  10629. // Remove from mesh
  10630. var index = this._mesh.subMeshes.indexOf(this);
  10631. this._mesh.subMeshes.splice(index, 1);
  10632. };
  10633. // Statics
  10634. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10635. var minVertexIndex = Number.MAX_VALUE;
  10636. var maxVertexIndex = -Number.MAX_VALUE;
  10637. renderingMesh = renderingMesh || mesh;
  10638. var indices = renderingMesh.getIndices();
  10639. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10640. var vertexIndex = indices[index];
  10641. if (vertexIndex < minVertexIndex)
  10642. minVertexIndex = vertexIndex;
  10643. if (vertexIndex > maxVertexIndex)
  10644. maxVertexIndex = vertexIndex;
  10645. }
  10646. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  10647. };
  10648. return SubMesh;
  10649. })();
  10650. BABYLON.SubMesh = SubMesh;
  10651. })(BABYLON || (BABYLON = {}));
  10652. //# sourceMappingURL=babylon.subMesh.js.map
  10653. var BABYLON;
  10654. (function (BABYLON) {
  10655. var BaseTexture = (function () {
  10656. function BaseTexture(scene) {
  10657. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10658. this.hasAlpha = false;
  10659. this.getAlphaFromRGB = false;
  10660. this.level = 1;
  10661. this.isCube = false;
  10662. this.isRenderTarget = false;
  10663. this.animations = new Array();
  10664. this.coordinatesIndex = 0;
  10665. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  10666. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10667. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10668. this.anisotropicFilteringLevel = 4;
  10669. this._scene = scene;
  10670. this._scene.textures.push(this);
  10671. }
  10672. BaseTexture.prototype.getScene = function () {
  10673. return this._scene;
  10674. };
  10675. BaseTexture.prototype.getTextureMatrix = function () {
  10676. return null;
  10677. };
  10678. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  10679. return null;
  10680. };
  10681. BaseTexture.prototype.getInternalTexture = function () {
  10682. return this._texture;
  10683. };
  10684. BaseTexture.prototype.isReady = function () {
  10685. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10686. return true;
  10687. }
  10688. if (this._texture) {
  10689. return this._texture.isReady;
  10690. }
  10691. return false;
  10692. };
  10693. BaseTexture.prototype.getSize = function () {
  10694. if (this._texture._width) {
  10695. return { width: this._texture._width, height: this._texture._height };
  10696. }
  10697. if (this._texture._size) {
  10698. return { width: this._texture._size, height: this._texture._size };
  10699. }
  10700. return { width: 0, height: 0 };
  10701. };
  10702. BaseTexture.prototype.getBaseSize = function () {
  10703. if (!this.isReady())
  10704. return { width: 0, height: 0 };
  10705. if (this._texture._size) {
  10706. return { width: this._texture._size, height: this._texture._size };
  10707. }
  10708. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  10709. };
  10710. BaseTexture.prototype.scale = function (ratio) {
  10711. };
  10712. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  10713. get: function () {
  10714. return false;
  10715. },
  10716. enumerable: true,
  10717. configurable: true
  10718. });
  10719. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  10720. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10721. for (var index = 0; index < texturesCache.length; index++) {
  10722. var texturesCacheEntry = texturesCache[index];
  10723. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10724. texturesCache.splice(index, 1);
  10725. return;
  10726. }
  10727. }
  10728. };
  10729. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  10730. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10731. for (var index = 0; index < texturesCache.length; index++) {
  10732. var texturesCacheEntry = texturesCache[index];
  10733. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10734. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  10735. texturesCacheEntry.references++;
  10736. return texturesCacheEntry;
  10737. }
  10738. }
  10739. }
  10740. return null;
  10741. };
  10742. BaseTexture.prototype.delayLoad = function () {
  10743. };
  10744. BaseTexture.prototype.releaseInternalTexture = function () {
  10745. if (!this._texture) {
  10746. return;
  10747. }
  10748. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10749. this._texture.references--;
  10750. // Final reference ?
  10751. if (this._texture.references === 0) {
  10752. var index = texturesCache.indexOf(this._texture);
  10753. texturesCache.splice(index, 1);
  10754. this._scene.getEngine()._releaseTexture(this._texture);
  10755. delete this._texture;
  10756. }
  10757. };
  10758. BaseTexture.prototype.clone = function () {
  10759. return null;
  10760. };
  10761. BaseTexture.prototype.dispose = function () {
  10762. // Remove from scene
  10763. var index = this._scene.textures.indexOf(this);
  10764. if (index >= 0) {
  10765. this._scene.textures.splice(index, 1);
  10766. }
  10767. if (this._texture === undefined) {
  10768. return;
  10769. }
  10770. this.releaseInternalTexture();
  10771. // Callback
  10772. if (this.onDispose) {
  10773. this.onDispose();
  10774. }
  10775. };
  10776. return BaseTexture;
  10777. })();
  10778. BABYLON.BaseTexture = BaseTexture;
  10779. })(BABYLON || (BABYLON = {}));
  10780. //# sourceMappingURL=babylon.baseTexture.js.map
  10781. var BABYLON;
  10782. (function (BABYLON) {
  10783. var RenderingGroup = (function () {
  10784. function RenderingGroup(index, scene) {
  10785. this.index = index;
  10786. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10787. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10788. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10789. this._scene = scene;
  10790. }
  10791. RenderingGroup.prototype.render = function (customRenderFunction) {
  10792. if (customRenderFunction) {
  10793. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10794. return true;
  10795. }
  10796. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10797. return false;
  10798. }
  10799. var engine = this._scene.getEngine();
  10800. // Opaque
  10801. var subIndex;
  10802. var submesh;
  10803. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10804. submesh = this._opaqueSubMeshes.data[subIndex];
  10805. submesh.render();
  10806. }
  10807. // Alpha test
  10808. engine.setAlphaTesting(true);
  10809. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10810. submesh = this._alphaTestSubMeshes.data[subIndex];
  10811. submesh.render();
  10812. }
  10813. engine.setAlphaTesting(false);
  10814. // Transparent
  10815. if (this._transparentSubMeshes.length) {
  10816. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10817. submesh = this._transparentSubMeshes.data[subIndex];
  10818. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10819. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10820. }
  10821. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10822. sortedArray.sort(function (a, b) {
  10823. // Alpha index first
  10824. if (a._alphaIndex > b._alphaIndex) {
  10825. return 1;
  10826. }
  10827. if (a._alphaIndex < b._alphaIndex) {
  10828. return -1;
  10829. }
  10830. // Then distance to camera
  10831. if (a._distanceToCamera < b._distanceToCamera) {
  10832. return 1;
  10833. }
  10834. if (a._distanceToCamera > b._distanceToCamera) {
  10835. return -1;
  10836. }
  10837. return 0;
  10838. });
  10839. // Rendering
  10840. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10841. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10842. submesh = sortedArray[subIndex];
  10843. submesh.render();
  10844. }
  10845. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10846. }
  10847. return true;
  10848. };
  10849. RenderingGroup.prototype.prepare = function () {
  10850. this._opaqueSubMeshes.reset();
  10851. this._transparentSubMeshes.reset();
  10852. this._alphaTestSubMeshes.reset();
  10853. };
  10854. RenderingGroup.prototype.dispatch = function (subMesh) {
  10855. var material = subMesh.getMaterial();
  10856. var mesh = subMesh.getMesh();
  10857. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10858. this._transparentSubMeshes.push(subMesh);
  10859. } else if (material.needAlphaTesting()) {
  10860. this._alphaTestSubMeshes.push(subMesh);
  10861. } else {
  10862. this._opaqueSubMeshes.push(subMesh); // Opaque
  10863. }
  10864. };
  10865. return RenderingGroup;
  10866. })();
  10867. BABYLON.RenderingGroup = RenderingGroup;
  10868. })(BABYLON || (BABYLON = {}));
  10869. //# sourceMappingURL=babylon.renderingGroup.js.map
  10870. var BABYLON;
  10871. (function (BABYLON) {
  10872. var RenderingManager = (function () {
  10873. function RenderingManager(scene) {
  10874. this._renderingGroups = new Array();
  10875. this._scene = scene;
  10876. }
  10877. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10878. if (this._scene._activeParticleSystems.length === 0) {
  10879. return;
  10880. }
  10881. // Particles
  10882. var beforeParticlesDate = BABYLON.Tools.Now;
  10883. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10884. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10885. if (particleSystem.renderingGroupId !== index) {
  10886. continue;
  10887. }
  10888. this._clearDepthBuffer();
  10889. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10890. this._scene._activeParticles += particleSystem.render();
  10891. }
  10892. }
  10893. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10894. };
  10895. RenderingManager.prototype._renderSprites = function (index) {
  10896. if (this._scene.spriteManagers.length === 0) {
  10897. return;
  10898. }
  10899. // Sprites
  10900. var beforeSpritessDate = BABYLON.Tools.Now;
  10901. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10902. var spriteManager = this._scene.spriteManagers[id];
  10903. if (spriteManager.renderingGroupId === index) {
  10904. this._clearDepthBuffer();
  10905. spriteManager.render();
  10906. }
  10907. }
  10908. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10909. };
  10910. RenderingManager.prototype._clearDepthBuffer = function () {
  10911. if (this._depthBufferAlreadyCleaned) {
  10912. return;
  10913. }
  10914. this._scene.getEngine().clear(0, false, true);
  10915. this._depthBufferAlreadyCleaned = true;
  10916. };
  10917. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10918. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10919. this._depthBufferAlreadyCleaned = false;
  10920. var renderingGroup = this._renderingGroups[index];
  10921. if (renderingGroup) {
  10922. this._clearDepthBuffer();
  10923. if (!renderingGroup.render(customRenderFunction)) {
  10924. this._renderingGroups.splice(index, 1);
  10925. }
  10926. }
  10927. this._renderSprites(index);
  10928. if (renderParticles) {
  10929. this._renderParticles(index, activeMeshes);
  10930. }
  10931. }
  10932. };
  10933. RenderingManager.prototype.reset = function () {
  10934. for (var index in this._renderingGroups) {
  10935. var renderingGroup = this._renderingGroups[index];
  10936. renderingGroup.prepare();
  10937. }
  10938. };
  10939. RenderingManager.prototype.dispatch = function (subMesh) {
  10940. var mesh = subMesh.getMesh();
  10941. var renderingGroupId = mesh.renderingGroupId || 0;
  10942. if (!this._renderingGroups[renderingGroupId]) {
  10943. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10944. }
  10945. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10946. };
  10947. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10948. return RenderingManager;
  10949. })();
  10950. BABYLON.RenderingManager = RenderingManager;
  10951. })(BABYLON || (BABYLON = {}));
  10952. //# sourceMappingURL=babylon.renderingManager.js.map
  10953. var BABYLON;
  10954. (function (BABYLON) {
  10955. var Texture = (function (_super) {
  10956. __extends(Texture, _super);
  10957. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  10958. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10959. if (typeof onLoad === "undefined") { onLoad = null; }
  10960. if (typeof onError === "undefined") { onError = null; }
  10961. if (typeof buffer === "undefined") { buffer = null; }
  10962. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  10963. _super.call(this, scene);
  10964. this.uOffset = 0;
  10965. this.vOffset = 0;
  10966. this.uScale = 1.0;
  10967. this.vScale = 1.0;
  10968. this.uAng = 0;
  10969. this.vAng = 0;
  10970. this.wAng = 0;
  10971. this.name = url;
  10972. this.url = url;
  10973. this._noMipmap = noMipmap;
  10974. this._invertY = invertY;
  10975. this._samplingMode = samplingMode;
  10976. this._buffer = buffer;
  10977. this._deleteBuffer = deleteBuffer;
  10978. if (!url) {
  10979. return;
  10980. }
  10981. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  10982. if (!this._texture) {
  10983. if (!scene.useDelayedTextureLoading) {
  10984. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  10985. if (deleteBuffer) {
  10986. delete this._buffer;
  10987. }
  10988. } else {
  10989. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10990. }
  10991. }
  10992. }
  10993. Texture.prototype.delayLoad = function () {
  10994. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10995. return;
  10996. }
  10997. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10998. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  10999. if (!this._texture) {
  11000. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11001. if (this._deleteBuffer) {
  11002. delete this._buffer;
  11003. }
  11004. }
  11005. };
  11006. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11007. x -= this.uOffset + 0.5;
  11008. y -= this.vOffset + 0.5;
  11009. z -= 0.5;
  11010. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11011. t.x *= this.uScale;
  11012. t.y *= this.vScale;
  11013. t.x += 0.5;
  11014. t.y += 0.5;
  11015. t.z += 0.5;
  11016. };
  11017. Texture.prototype.getTextureMatrix = function () {
  11018. 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) {
  11019. return this._cachedTextureMatrix;
  11020. }
  11021. this._cachedUOffset = this.uOffset;
  11022. this._cachedVOffset = this.vOffset;
  11023. this._cachedUScale = this.uScale;
  11024. this._cachedVScale = this.vScale;
  11025. this._cachedUAng = this.uAng;
  11026. this._cachedVAng = this.vAng;
  11027. this._cachedWAng = this.wAng;
  11028. if (!this._cachedTextureMatrix) {
  11029. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11030. this._rowGenerationMatrix = new BABYLON.Matrix();
  11031. this._t0 = BABYLON.Vector3.Zero();
  11032. this._t1 = BABYLON.Vector3.Zero();
  11033. this._t2 = BABYLON.Vector3.Zero();
  11034. }
  11035. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11036. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11037. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11038. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11039. this._t1.subtractInPlace(this._t0);
  11040. this._t2.subtractInPlace(this._t0);
  11041. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11042. this._cachedTextureMatrix.m[0] = this._t1.x;
  11043. this._cachedTextureMatrix.m[1] = this._t1.y;
  11044. this._cachedTextureMatrix.m[2] = this._t1.z;
  11045. this._cachedTextureMatrix.m[4] = this._t2.x;
  11046. this._cachedTextureMatrix.m[5] = this._t2.y;
  11047. this._cachedTextureMatrix.m[6] = this._t2.z;
  11048. this._cachedTextureMatrix.m[8] = this._t0.x;
  11049. this._cachedTextureMatrix.m[9] = this._t0.y;
  11050. this._cachedTextureMatrix.m[10] = this._t0.z;
  11051. return this._cachedTextureMatrix;
  11052. };
  11053. Texture.prototype.getReflectionTextureMatrix = function () {
  11054. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11055. return this._cachedTextureMatrix;
  11056. }
  11057. if (!this._cachedTextureMatrix) {
  11058. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11059. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11060. }
  11061. this._cachedCoordinatesMode = this.coordinatesMode;
  11062. switch (this.coordinatesMode) {
  11063. case BABYLON.Texture.SPHERICAL_MODE:
  11064. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11065. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11066. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11067. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11068. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11069. break;
  11070. case BABYLON.Texture.PLANAR_MODE:
  11071. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11072. this._cachedTextureMatrix[0] = this.uScale;
  11073. this._cachedTextureMatrix[5] = this.vScale;
  11074. this._cachedTextureMatrix[12] = this.uOffset;
  11075. this._cachedTextureMatrix[13] = this.vOffset;
  11076. break;
  11077. case BABYLON.Texture.PROJECTION_MODE:
  11078. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11079. this._projectionModeMatrix.m[0] = 0.5;
  11080. this._projectionModeMatrix.m[5] = -0.5;
  11081. this._projectionModeMatrix.m[10] = 0.0;
  11082. this._projectionModeMatrix.m[12] = 0.5;
  11083. this._projectionModeMatrix.m[13] = 0.5;
  11084. this._projectionModeMatrix.m[14] = 1.0;
  11085. this._projectionModeMatrix.m[15] = 1.0;
  11086. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11087. break;
  11088. default:
  11089. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11090. break;
  11091. }
  11092. return this._cachedTextureMatrix;
  11093. };
  11094. Texture.prototype.clone = function () {
  11095. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  11096. // Base texture
  11097. newTexture.hasAlpha = this.hasAlpha;
  11098. newTexture.level = this.level;
  11099. newTexture.wrapU = this.wrapU;
  11100. newTexture.wrapV = this.wrapV;
  11101. newTexture.coordinatesIndex = this.coordinatesIndex;
  11102. newTexture.coordinatesMode = this.coordinatesMode;
  11103. // Texture
  11104. newTexture.uOffset = this.uOffset;
  11105. newTexture.vOffset = this.vOffset;
  11106. newTexture.uScale = this.uScale;
  11107. newTexture.vScale = this.vScale;
  11108. newTexture.uAng = this.uAng;
  11109. newTexture.vAng = this.vAng;
  11110. newTexture.wAng = this.wAng;
  11111. return newTexture;
  11112. };
  11113. // Statics
  11114. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11115. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11116. if (typeof onLoad === "undefined") { onLoad = null; }
  11117. if (typeof onError === "undefined") { onError = null; }
  11118. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11119. };
  11120. Texture.NEAREST_SAMPLINGMODE = 1;
  11121. Texture.BILINEAR_SAMPLINGMODE = 2;
  11122. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11123. Texture.EXPLICIT_MODE = 0;
  11124. Texture.SPHERICAL_MODE = 1;
  11125. Texture.PLANAR_MODE = 2;
  11126. Texture.CUBIC_MODE = 3;
  11127. Texture.PROJECTION_MODE = 4;
  11128. Texture.SKYBOX_MODE = 5;
  11129. Texture.CLAMP_ADDRESSMODE = 0;
  11130. Texture.WRAP_ADDRESSMODE = 1;
  11131. Texture.MIRROR_ADDRESSMODE = 2;
  11132. return Texture;
  11133. })(BABYLON.BaseTexture);
  11134. BABYLON.Texture = Texture;
  11135. })(BABYLON || (BABYLON = {}));
  11136. //# sourceMappingURL=babylon.texture.js.map
  11137. var BABYLON;
  11138. (function (BABYLON) {
  11139. var CubeTexture = (function (_super) {
  11140. __extends(CubeTexture, _super);
  11141. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11142. _super.call(this, scene);
  11143. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11144. this.name = rootUrl;
  11145. this.url = rootUrl;
  11146. this._noMipmap = noMipmap;
  11147. this.hasAlpha = false;
  11148. this._texture = this._getFromCache(rootUrl, noMipmap);
  11149. if (!extensions) {
  11150. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11151. }
  11152. this._extensions = extensions;
  11153. if (!this._texture) {
  11154. if (!scene.useDelayedTextureLoading) {
  11155. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11156. } else {
  11157. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11158. }
  11159. }
  11160. this.isCube = true;
  11161. this._textureMatrix = BABYLON.Matrix.Identity();
  11162. }
  11163. CubeTexture.prototype.clone = function () {
  11164. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11165. // Base texture
  11166. newTexture.level = this.level;
  11167. newTexture.wrapU = this.wrapU;
  11168. newTexture.wrapV = this.wrapV;
  11169. newTexture.coordinatesIndex = this.coordinatesIndex;
  11170. newTexture.coordinatesMode = this.coordinatesMode;
  11171. return newTexture;
  11172. };
  11173. // Methods
  11174. CubeTexture.prototype.delayLoad = function () {
  11175. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11176. return;
  11177. }
  11178. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11179. this._texture = this._getFromCache(this.url, this._noMipmap);
  11180. if (!this._texture) {
  11181. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11182. }
  11183. };
  11184. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11185. return this._textureMatrix;
  11186. };
  11187. return CubeTexture;
  11188. })(BABYLON.BaseTexture);
  11189. BABYLON.CubeTexture = CubeTexture;
  11190. })(BABYLON || (BABYLON = {}));
  11191. //# sourceMappingURL=babylon.cubeTexture.js.map
  11192. var BABYLON;
  11193. (function (BABYLON) {
  11194. var RenderTargetTexture = (function (_super) {
  11195. __extends(RenderTargetTexture, _super);
  11196. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  11197. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  11198. _super.call(this, null, scene, !generateMipMaps);
  11199. this.renderList = new Array();
  11200. this.renderParticles = true;
  11201. this.renderSprites = false;
  11202. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11203. this._currentRefreshId = -1;
  11204. this._refreshRate = 1;
  11205. this.name = name;
  11206. this.isRenderTarget = true;
  11207. this._size = size;
  11208. this._generateMipMaps = generateMipMaps;
  11209. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11210. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11211. // Rendering groups
  11212. this._renderingManager = new BABYLON.RenderingManager(scene);
  11213. }
  11214. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11215. this._currentRefreshId = -1;
  11216. };
  11217. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11218. get: function () {
  11219. return this._refreshRate;
  11220. },
  11221. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11222. set: function (value) {
  11223. this._refreshRate = value;
  11224. this.resetRefreshCounter();
  11225. },
  11226. enumerable: true,
  11227. configurable: true
  11228. });
  11229. RenderTargetTexture.prototype._shouldRender = function () {
  11230. if (this._currentRefreshId === -1) {
  11231. this._currentRefreshId = 1;
  11232. return true;
  11233. }
  11234. if (this.refreshRate == this._currentRefreshId) {
  11235. this._currentRefreshId = 1;
  11236. return true;
  11237. }
  11238. this._currentRefreshId++;
  11239. return false;
  11240. };
  11241. RenderTargetTexture.prototype.isReady = function () {
  11242. if (!this.getScene().renderTargetsEnabled) {
  11243. return false;
  11244. }
  11245. return _super.prototype.isReady.call(this);
  11246. };
  11247. RenderTargetTexture.prototype.getRenderSize = function () {
  11248. return this._size;
  11249. };
  11250. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11251. get: function () {
  11252. return true;
  11253. },
  11254. enumerable: true,
  11255. configurable: true
  11256. });
  11257. RenderTargetTexture.prototype.scale = function (ratio) {
  11258. var newSize = this._size * ratio;
  11259. this.resize(newSize, this._generateMipMaps);
  11260. };
  11261. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11262. this.releaseInternalTexture();
  11263. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11264. };
  11265. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11266. var scene = this.getScene();
  11267. var engine = scene.getEngine();
  11268. if (this._waitingRenderList) {
  11269. this.renderList = [];
  11270. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11271. var id = this._waitingRenderList[index];
  11272. this.renderList.push(scene.getMeshByID(id));
  11273. }
  11274. delete this._waitingRenderList;
  11275. }
  11276. if (!this.renderList) {
  11277. return;
  11278. }
  11279. // Bind
  11280. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11281. engine.bindFramebuffer(this._texture);
  11282. }
  11283. // Clear
  11284. engine.clear(scene.clearColor, true, true);
  11285. this._renderingManager.reset();
  11286. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  11287. var mesh = this.renderList[meshIndex];
  11288. if (mesh) {
  11289. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11290. // Reset _currentRefreshId
  11291. this.resetRefreshCounter();
  11292. continue;
  11293. }
  11294. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  11295. mesh._activate(scene.getRenderId());
  11296. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11297. var subMesh = mesh.subMeshes[subIndex];
  11298. scene._activeVertices += subMesh.indexCount;
  11299. this._renderingManager.dispatch(subMesh);
  11300. }
  11301. }
  11302. }
  11303. }
  11304. if (!this._doNotChangeAspectRatio) {
  11305. scene.updateTransformMatrix(true);
  11306. }
  11307. if (this.onBeforeRender) {
  11308. this.onBeforeRender();
  11309. }
  11310. // Render
  11311. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  11312. if (useCameraPostProcess) {
  11313. scene.postProcessManager._finalizeFrame(false, this._texture);
  11314. }
  11315. if (this.onAfterRender) {
  11316. this.onAfterRender();
  11317. }
  11318. // Unbind
  11319. engine.unBindFramebuffer(this._texture);
  11320. if (!this._doNotChangeAspectRatio) {
  11321. scene.updateTransformMatrix(true);
  11322. }
  11323. };
  11324. RenderTargetTexture.prototype.clone = function () {
  11325. var textureSize = this.getSize();
  11326. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11327. // Base texture
  11328. newTexture.hasAlpha = this.hasAlpha;
  11329. newTexture.level = this.level;
  11330. // RenderTarget Texture
  11331. newTexture.coordinatesMode = this.coordinatesMode;
  11332. newTexture.renderList = this.renderList.slice(0);
  11333. return newTexture;
  11334. };
  11335. return RenderTargetTexture;
  11336. })(BABYLON.Texture);
  11337. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11338. })(BABYLON || (BABYLON = {}));
  11339. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11340. var BABYLON;
  11341. (function (BABYLON) {
  11342. var ProceduralTexture = (function (_super) {
  11343. __extends(ProceduralTexture, _super);
  11344. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11345. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  11346. _super.call(this, null, scene, !generateMipMaps);
  11347. this._currentRefreshId = -1;
  11348. this._refreshRate = 1;
  11349. this._vertexDeclaration = [2];
  11350. this._vertexStrideSize = 2 * 4;
  11351. this._uniforms = new Array();
  11352. this._samplers = new Array();
  11353. this._textures = new Array();
  11354. this._floats = new Array();
  11355. this._floatsArrays = {};
  11356. this._colors3 = new Array();
  11357. this._colors4 = new Array();
  11358. this._vectors2 = new Array();
  11359. this._vectors3 = new Array();
  11360. this._matrices = new Array();
  11361. this._fallbackTextureUsed = false;
  11362. scene._proceduralTextures.push(this);
  11363. this.name = name;
  11364. this.isRenderTarget = true;
  11365. this._size = size;
  11366. this._generateMipMaps = generateMipMaps;
  11367. this.setFragment(fragment);
  11368. this._fallbackTexture = fallbackTexture;
  11369. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11370. // VBO
  11371. var vertices = [];
  11372. vertices.push(1, 1);
  11373. vertices.push(-1, 1);
  11374. vertices.push(-1, -1);
  11375. vertices.push(1, -1);
  11376. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11377. // Indices
  11378. var indices = [];
  11379. indices.push(0);
  11380. indices.push(1);
  11381. indices.push(2);
  11382. indices.push(0);
  11383. indices.push(2);
  11384. indices.push(3);
  11385. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11386. }
  11387. ProceduralTexture.prototype.reset = function () {
  11388. if (this._effect === undefined) {
  11389. return;
  11390. }
  11391. var engine = this.getScene().getEngine();
  11392. engine._releaseEffect(this._effect);
  11393. };
  11394. ProceduralTexture.prototype.isReady = function () {
  11395. var _this = this;
  11396. var engine = this.getScene().getEngine();
  11397. var shaders;
  11398. if (!this._fragment) {
  11399. return false;
  11400. }
  11401. if (this._fallbackTextureUsed) {
  11402. return true;
  11403. }
  11404. if (this._fragment.fragmentElement !== undefined) {
  11405. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11406. } else {
  11407. shaders = { vertex: "procedural", fragment: this._fragment };
  11408. }
  11409. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11410. _this.releaseInternalTexture();
  11411. if (_this._fallbackTexture) {
  11412. _this._texture = _this._fallbackTexture._texture;
  11413. _this._texture.references++;
  11414. }
  11415. _this._fallbackTextureUsed = true;
  11416. });
  11417. return this._effect.isReady();
  11418. };
  11419. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11420. this._currentRefreshId = -1;
  11421. };
  11422. ProceduralTexture.prototype.setFragment = function (fragment) {
  11423. this._fragment = fragment;
  11424. };
  11425. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11426. get: function () {
  11427. return this._refreshRate;
  11428. },
  11429. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11430. set: function (value) {
  11431. this._refreshRate = value;
  11432. this.resetRefreshCounter();
  11433. },
  11434. enumerable: true,
  11435. configurable: true
  11436. });
  11437. ProceduralTexture.prototype._shouldRender = function () {
  11438. if (!this.isReady() || !this._texture) {
  11439. return false;
  11440. }
  11441. if (this._fallbackTextureUsed) {
  11442. return false;
  11443. }
  11444. if (this._currentRefreshId === -1) {
  11445. this._currentRefreshId = 1;
  11446. return true;
  11447. }
  11448. if (this.refreshRate === this._currentRefreshId) {
  11449. this._currentRefreshId = 1;
  11450. return true;
  11451. }
  11452. this._currentRefreshId++;
  11453. return false;
  11454. };
  11455. ProceduralTexture.prototype.getRenderSize = function () {
  11456. return this._size;
  11457. };
  11458. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11459. if (this._fallbackTextureUsed) {
  11460. return;
  11461. }
  11462. this.releaseInternalTexture();
  11463. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11464. };
  11465. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11466. if (this._uniforms.indexOf(uniformName) === -1) {
  11467. this._uniforms.push(uniformName);
  11468. }
  11469. };
  11470. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11471. if (this._samplers.indexOf(name) === -1) {
  11472. this._samplers.push(name);
  11473. }
  11474. this._textures[name] = texture;
  11475. return this;
  11476. };
  11477. ProceduralTexture.prototype.setFloat = function (name, value) {
  11478. this._checkUniform(name);
  11479. this._floats[name] = value;
  11480. return this;
  11481. };
  11482. ProceduralTexture.prototype.setFloats = function (name, value) {
  11483. this._checkUniform(name);
  11484. this._floatsArrays[name] = value;
  11485. return this;
  11486. };
  11487. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11488. this._checkUniform(name);
  11489. this._colors3[name] = value;
  11490. return this;
  11491. };
  11492. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11493. this._checkUniform(name);
  11494. this._colors4[name] = value;
  11495. return this;
  11496. };
  11497. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11498. this._checkUniform(name);
  11499. this._vectors2[name] = value;
  11500. return this;
  11501. };
  11502. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11503. this._checkUniform(name);
  11504. this._vectors3[name] = value;
  11505. return this;
  11506. };
  11507. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11508. this._checkUniform(name);
  11509. this._matrices[name] = value;
  11510. return this;
  11511. };
  11512. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11513. var scene = this.getScene();
  11514. var engine = scene.getEngine();
  11515. engine.bindFramebuffer(this._texture);
  11516. // Clear
  11517. engine.clear(scene.clearColor, true, true);
  11518. // Render
  11519. engine.enableEffect(this._effect);
  11520. engine.setState(false);
  11521. for (var name in this._textures) {
  11522. this._effect.setTexture(name, this._textures[name]);
  11523. }
  11524. for (name in this._floats) {
  11525. this._effect.setFloat(name, this._floats[name]);
  11526. }
  11527. for (name in this._floatsArrays) {
  11528. this._effect.setArray(name, this._floatsArrays[name]);
  11529. }
  11530. for (name in this._colors3) {
  11531. this._effect.setColor3(name, this._colors3[name]);
  11532. }
  11533. for (name in this._colors4) {
  11534. var color = this._colors4[name];
  11535. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  11536. }
  11537. for (name in this._vectors2) {
  11538. this._effect.setVector2(name, this._vectors2[name]);
  11539. }
  11540. for (name in this._vectors3) {
  11541. this._effect.setVector3(name, this._vectors3[name]);
  11542. }
  11543. for (name in this._matrices) {
  11544. this._effect.setMatrix(name, this._matrices[name]);
  11545. }
  11546. // VBOs
  11547. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11548. // Draw order
  11549. engine.draw(true, 0, 6);
  11550. // Unbind
  11551. engine.unBindFramebuffer(this._texture);
  11552. };
  11553. ProceduralTexture.prototype.clone = function () {
  11554. var textureSize = this.getSize();
  11555. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  11556. // Base texture
  11557. newTexture.hasAlpha = this.hasAlpha;
  11558. newTexture.level = this.level;
  11559. // RenderTarget Texture
  11560. newTexture.coordinatesMode = this.coordinatesMode;
  11561. return newTexture;
  11562. };
  11563. ProceduralTexture.prototype.dispose = function () {
  11564. var index = this.getScene()._proceduralTextures.indexOf(this);
  11565. if (index >= 0) {
  11566. this.getScene()._proceduralTextures.splice(index, 1);
  11567. }
  11568. _super.prototype.dispose.call(this);
  11569. };
  11570. return ProceduralTexture;
  11571. })(BABYLON.Texture);
  11572. BABYLON.ProceduralTexture = ProceduralTexture;
  11573. })(BABYLON || (BABYLON = {}));
  11574. //# sourceMappingURL=babylon.proceduralTexture.js.map
  11575. var BABYLON;
  11576. (function (BABYLON) {
  11577. var WoodProceduralTexture = (function (_super) {
  11578. __extends(WoodProceduralTexture, _super);
  11579. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11580. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  11581. this._ampScale = 100.0;
  11582. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  11583. this.updateShaderUniforms();
  11584. this.refreshRate = 0;
  11585. }
  11586. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  11587. this.setFloat("ampScale", this._ampScale);
  11588. this.setColor3("woodColor", this._woodColor);
  11589. };
  11590. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  11591. get: function () {
  11592. return this._ampScale;
  11593. },
  11594. set: function (value) {
  11595. this._ampScale = value;
  11596. this.updateShaderUniforms();
  11597. },
  11598. enumerable: true,
  11599. configurable: true
  11600. });
  11601. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  11602. get: function () {
  11603. return this._woodColor;
  11604. },
  11605. set: function (value) {
  11606. this._woodColor = value;
  11607. this.updateShaderUniforms();
  11608. },
  11609. enumerable: true,
  11610. configurable: true
  11611. });
  11612. return WoodProceduralTexture;
  11613. })(BABYLON.ProceduralTexture);
  11614. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  11615. var FireProceduralTexture = (function (_super) {
  11616. __extends(FireProceduralTexture, _super);
  11617. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11618. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  11619. this._time = 0.0;
  11620. this._speed = new BABYLON.Vector2(0.5, 0.3);
  11621. this._shift = 1.6;
  11622. this._autoGenerateTime = true;
  11623. this._alphaThreshold = 0.5;
  11624. this._fireColors = FireProceduralTexture.RedFireColors;
  11625. this.updateShaderUniforms();
  11626. this.refreshRate = 1;
  11627. }
  11628. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  11629. this.setFloat("time", this._time);
  11630. this.setVector2("speed", this._speed);
  11631. this.setFloat("shift", this._shift);
  11632. this.setColor3("c1", this._fireColors[0]);
  11633. this.setColor3("c2", this._fireColors[1]);
  11634. this.setColor3("c3", this._fireColors[2]);
  11635. this.setColor3("c4", this._fireColors[3]);
  11636. this.setColor3("c5", this._fireColors[4]);
  11637. this.setColor3("c6", this._fireColors[5]);
  11638. this.setFloat("alphaThreshold", this._alphaThreshold);
  11639. };
  11640. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11641. if (this._autoGenerateTime) {
  11642. this._time += this.getScene().getAnimationRatio() * 0.03;
  11643. this.updateShaderUniforms();
  11644. }
  11645. _super.prototype.render.call(this, useCameraPostProcess);
  11646. };
  11647. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  11648. get: function () {
  11649. return [
  11650. new BABYLON.Color3(0.5, 0.0, 1.0),
  11651. new BABYLON.Color3(0.9, 0.0, 1.0),
  11652. new BABYLON.Color3(0.2, 0.0, 1.0),
  11653. new BABYLON.Color3(1.0, 0.9, 1.0),
  11654. new BABYLON.Color3(0.1, 0.1, 1.0),
  11655. new BABYLON.Color3(0.9, 0.9, 1.0)
  11656. ];
  11657. },
  11658. enumerable: true,
  11659. configurable: true
  11660. });
  11661. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  11662. get: function () {
  11663. return [
  11664. new BABYLON.Color3(0.5, 1.0, 0.0),
  11665. new BABYLON.Color3(0.5, 1.0, 0.0),
  11666. new BABYLON.Color3(0.3, 0.4, 0.0),
  11667. new BABYLON.Color3(0.5, 1.0, 0.0),
  11668. new BABYLON.Color3(0.2, 0.0, 0.0),
  11669. new BABYLON.Color3(0.5, 1.0, 0.0)
  11670. ];
  11671. },
  11672. enumerable: true,
  11673. configurable: true
  11674. });
  11675. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  11676. get: function () {
  11677. return [
  11678. new BABYLON.Color3(0.5, 0.0, 0.1),
  11679. new BABYLON.Color3(0.9, 0.0, 0.0),
  11680. new BABYLON.Color3(0.2, 0.0, 0.0),
  11681. new BABYLON.Color3(1.0, 0.9, 0.0),
  11682. new BABYLON.Color3(0.1, 0.1, 0.1),
  11683. new BABYLON.Color3(0.9, 0.9, 0.9)
  11684. ];
  11685. },
  11686. enumerable: true,
  11687. configurable: true
  11688. });
  11689. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  11690. get: function () {
  11691. return [
  11692. new BABYLON.Color3(0.1, 0.0, 0.5),
  11693. new BABYLON.Color3(0.0, 0.0, 0.5),
  11694. new BABYLON.Color3(0.1, 0.0, 0.2),
  11695. new BABYLON.Color3(0.0, 0.0, 1.0),
  11696. new BABYLON.Color3(0.1, 0.2, 0.3),
  11697. new BABYLON.Color3(0.0, 0.2, 0.9)
  11698. ];
  11699. },
  11700. enumerable: true,
  11701. configurable: true
  11702. });
  11703. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  11704. get: function () {
  11705. return this._fireColors;
  11706. },
  11707. set: function (value) {
  11708. this._fireColors = value;
  11709. this.updateShaderUniforms();
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  11715. get: function () {
  11716. return this._time;
  11717. },
  11718. set: function (value) {
  11719. this._time = value;
  11720. this.updateShaderUniforms();
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  11726. get: function () {
  11727. return this._speed;
  11728. },
  11729. set: function (value) {
  11730. this._speed = value;
  11731. this.updateShaderUniforms();
  11732. },
  11733. enumerable: true,
  11734. configurable: true
  11735. });
  11736. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  11737. get: function () {
  11738. return this._shift;
  11739. },
  11740. set: function (value) {
  11741. this._shift = value;
  11742. this.updateShaderUniforms();
  11743. },
  11744. enumerable: true,
  11745. configurable: true
  11746. });
  11747. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  11748. get: function () {
  11749. return this._alphaThreshold;
  11750. },
  11751. set: function (value) {
  11752. this._alphaThreshold = value;
  11753. this.updateShaderUniforms();
  11754. },
  11755. enumerable: true,
  11756. configurable: true
  11757. });
  11758. return FireProceduralTexture;
  11759. })(BABYLON.ProceduralTexture);
  11760. BABYLON.FireProceduralTexture = FireProceduralTexture;
  11761. var CloudProceduralTexture = (function (_super) {
  11762. __extends(CloudProceduralTexture, _super);
  11763. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11764. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  11765. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  11766. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  11767. this.updateShaderUniforms();
  11768. this.refreshRate = 0;
  11769. }
  11770. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  11771. this.setColor3("skyColor", this._skyColor);
  11772. this.setColor3("cloudColor", this._cloudColor);
  11773. };
  11774. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  11775. get: function () {
  11776. return this._skyColor;
  11777. },
  11778. set: function (value) {
  11779. this._skyColor = value;
  11780. this.updateShaderUniforms();
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  11786. get: function () {
  11787. return this._cloudColor;
  11788. },
  11789. set: function (value) {
  11790. this._cloudColor = value;
  11791. this.updateShaderUniforms();
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. return CloudProceduralTexture;
  11797. })(BABYLON.ProceduralTexture);
  11798. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  11799. var GrassProceduralTexture = (function (_super) {
  11800. __extends(GrassProceduralTexture, _super);
  11801. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11802. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  11803. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  11804. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  11805. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  11806. this._groundColor = new BABYLON.Color3(1, 1, 1);
  11807. this._grassColors = [
  11808. new BABYLON.Color3(0.29, 0.38, 0.02),
  11809. new BABYLON.Color3(0.36, 0.49, 0.09),
  11810. new BABYLON.Color3(0.51, 0.6, 0.28)
  11811. ];
  11812. this.updateShaderUniforms();
  11813. this.refreshRate = 0;
  11814. }
  11815. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  11816. this.setColor3("herb1Color", this._grassColors[0]);
  11817. this.setColor3("herb2Color", this._grassColors[1]);
  11818. this.setColor3("herb3Color", this._grassColors[2]);
  11819. this.setColor3("groundColor", this._groundColor);
  11820. };
  11821. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  11822. get: function () {
  11823. return this._grassColors;
  11824. },
  11825. set: function (value) {
  11826. this._grassColors = value;
  11827. this.updateShaderUniforms();
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  11833. get: function () {
  11834. return this._groundColor;
  11835. },
  11836. set: function (value) {
  11837. this.groundColor = value;
  11838. this.updateShaderUniforms();
  11839. },
  11840. enumerable: true,
  11841. configurable: true
  11842. });
  11843. return GrassProceduralTexture;
  11844. })(BABYLON.ProceduralTexture);
  11845. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  11846. var RoadProceduralTexture = (function (_super) {
  11847. __extends(RoadProceduralTexture, _super);
  11848. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11849. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  11850. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  11851. this.updateShaderUniforms();
  11852. this.refreshRate = 0;
  11853. }
  11854. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  11855. this.setColor3("roadColor", this._roadColor);
  11856. };
  11857. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  11858. get: function () {
  11859. return this._roadColor;
  11860. },
  11861. set: function (value) {
  11862. this._roadColor = value;
  11863. this.updateShaderUniforms();
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. return RoadProceduralTexture;
  11869. })(BABYLON.ProceduralTexture);
  11870. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  11871. var BrickProceduralTexture = (function (_super) {
  11872. __extends(BrickProceduralTexture, _super);
  11873. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11874. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  11875. this._numberOfBricksHeight = 15;
  11876. this._numberOfBricksWidth = 5;
  11877. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11878. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11879. this.updateShaderUniforms();
  11880. this.refreshRate = 0;
  11881. }
  11882. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  11883. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  11884. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  11885. this.setColor3("brickColor", this._brickColor);
  11886. this.setColor3("jointColor", this._jointColor);
  11887. };
  11888. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  11889. get: function () {
  11890. return this._numberOfBricksHeight;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  11896. set: function (value) {
  11897. this._numberOfBricksHeight = value;
  11898. this.updateShaderUniforms();
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  11904. get: function () {
  11905. return this._numberOfBricksWidth;
  11906. },
  11907. set: function (value) {
  11908. this._numberOfBricksHeight = value;
  11909. this.updateShaderUniforms();
  11910. },
  11911. enumerable: true,
  11912. configurable: true
  11913. });
  11914. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  11915. get: function () {
  11916. return this._jointColor;
  11917. },
  11918. set: function (value) {
  11919. this._jointColor = value;
  11920. this.updateShaderUniforms();
  11921. },
  11922. enumerable: true,
  11923. configurable: true
  11924. });
  11925. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  11926. get: function () {
  11927. return this._brickColor;
  11928. },
  11929. set: function (value) {
  11930. this._brickColor = value;
  11931. this.updateShaderUniforms();
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. return BrickProceduralTexture;
  11937. })(BABYLON.ProceduralTexture);
  11938. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  11939. var MarbleProceduralTexture = (function (_super) {
  11940. __extends(MarbleProceduralTexture, _super);
  11941. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11942. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  11943. this._numberOfTilesHeight = 3;
  11944. this._numberOfTilesWidth = 3;
  11945. this._amplitude = 9.0;
  11946. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11947. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11948. this.updateShaderUniforms();
  11949. this.refreshRate = 0;
  11950. }
  11951. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  11952. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  11953. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  11954. this.setFloat("amplitude", this._amplitude);
  11955. this.setColor3("marbleColor", this._marbleColor);
  11956. this.setColor3("jointColor", this._jointColor);
  11957. };
  11958. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  11959. get: function () {
  11960. return this._numberOfTilesHeight;
  11961. },
  11962. set: function (value) {
  11963. this._numberOfTilesHeight = value;
  11964. this.updateShaderUniforms();
  11965. },
  11966. enumerable: true,
  11967. configurable: true
  11968. });
  11969. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  11970. get: function () {
  11971. return this._numberOfTilesWidth;
  11972. },
  11973. set: function (value) {
  11974. this._numberOfTilesWidth = value;
  11975. this.updateShaderUniforms();
  11976. },
  11977. enumerable: true,
  11978. configurable: true
  11979. });
  11980. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  11981. get: function () {
  11982. return this._jointColor;
  11983. },
  11984. set: function (value) {
  11985. this._jointColor = value;
  11986. this.updateShaderUniforms();
  11987. },
  11988. enumerable: true,
  11989. configurable: true
  11990. });
  11991. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  11992. get: function () {
  11993. return this._marbleColor;
  11994. },
  11995. set: function (value) {
  11996. this._marbleColor = value;
  11997. this.updateShaderUniforms();
  11998. },
  11999. enumerable: true,
  12000. configurable: true
  12001. });
  12002. return MarbleProceduralTexture;
  12003. })(BABYLON.ProceduralTexture);
  12004. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12005. })(BABYLON || (BABYLON = {}));
  12006. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12007. var BABYLON;
  12008. (function (BABYLON) {
  12009. var CustomProceduralTexture = (function (_super) {
  12010. __extends(CustomProceduralTexture, _super);
  12011. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12012. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12013. this._animate = true;
  12014. this._time = 0;
  12015. this._texturePath = texturePath;
  12016. //Try to load json
  12017. this.loadJson(texturePath);
  12018. this.refreshRate = 1;
  12019. }
  12020. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12021. var _this = this;
  12022. var that = this;
  12023. function noConfigFile() {
  12024. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  12025. try {
  12026. that.setFragment(that._texturePath);
  12027. } catch (ex) {
  12028. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12029. }
  12030. }
  12031. var configFileUrl = jsonUrl + "/config.json";
  12032. var xhr = new XMLHttpRequest();
  12033. xhr.open("GET", configFileUrl, true);
  12034. xhr.addEventListener("load", function () {
  12035. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12036. try {
  12037. _this._config = JSON.parse(xhr.response);
  12038. _this.updateShaderUniforms();
  12039. _this.updateTextures();
  12040. _this.setFragment(_this._texturePath + "/custom");
  12041. _this._animate = _this._config.animate;
  12042. _this.refreshRate = _this._config.refreshrate;
  12043. } catch (ex) {
  12044. noConfigFile();
  12045. }
  12046. } else {
  12047. noConfigFile();
  12048. }
  12049. }, false);
  12050. xhr.addEventListener("error", function (event) {
  12051. noConfigFile();
  12052. }, false);
  12053. try {
  12054. xhr.send();
  12055. } catch (ex) {
  12056. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12057. }
  12058. };
  12059. CustomProceduralTexture.prototype.isReady = function () {
  12060. if (!_super.prototype.isReady.call(this)) {
  12061. return false;
  12062. }
  12063. for (var name in this._textures) {
  12064. var texture = this._textures[name];
  12065. if (!texture.isReady()) {
  12066. return false;
  12067. }
  12068. }
  12069. return true;
  12070. };
  12071. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12072. if (this._animate) {
  12073. this._time += this.getScene().getAnimationRatio() * 0.03;
  12074. this.updateShaderUniforms();
  12075. }
  12076. _super.prototype.render.call(this, useCameraPostProcess);
  12077. };
  12078. CustomProceduralTexture.prototype.updateTextures = function () {
  12079. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12080. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12081. }
  12082. };
  12083. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12084. if (this._config) {
  12085. for (var j = 0; j < this._config.uniforms.length; j++) {
  12086. var uniform = this._config.uniforms[j];
  12087. switch (uniform.type) {
  12088. case "float":
  12089. this.setFloat(uniform.name, uniform.value);
  12090. break;
  12091. case "color3":
  12092. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12093. break;
  12094. case "color4":
  12095. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12096. break;
  12097. case "vector2":
  12098. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12099. break;
  12100. case "vector3":
  12101. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12102. break;
  12103. }
  12104. }
  12105. }
  12106. this.setFloat("time", this._time);
  12107. };
  12108. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12109. get: function () {
  12110. return this._animate;
  12111. },
  12112. set: function (value) {
  12113. this._animate = value;
  12114. },
  12115. enumerable: true,
  12116. configurable: true
  12117. });
  12118. return CustomProceduralTexture;
  12119. })(BABYLON.ProceduralTexture);
  12120. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12121. })(BABYLON || (BABYLON = {}));
  12122. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12123. var BABYLON;
  12124. (function (BABYLON) {
  12125. var MirrorTexture = (function (_super) {
  12126. __extends(MirrorTexture, _super);
  12127. function MirrorTexture(name, size, scene, generateMipMaps) {
  12128. var _this = this;
  12129. _super.call(this, name, size, scene, generateMipMaps, true);
  12130. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12131. this._transformMatrix = BABYLON.Matrix.Zero();
  12132. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12133. this.onBeforeRender = function () {
  12134. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12135. _this._savedViewMatrix = scene.getViewMatrix();
  12136. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12137. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12138. scene.clipPlane = _this.mirrorPlane;
  12139. scene.getEngine().cullBackFaces = false;
  12140. };
  12141. this.onAfterRender = function () {
  12142. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12143. scene.getEngine().cullBackFaces = true;
  12144. delete scene.clipPlane;
  12145. };
  12146. }
  12147. MirrorTexture.prototype.clone = function () {
  12148. var textureSize = this.getSize();
  12149. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12150. // Base texture
  12151. newTexture.hasAlpha = this.hasAlpha;
  12152. newTexture.level = this.level;
  12153. // Mirror Texture
  12154. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12155. newTexture.renderList = this.renderList.slice(0);
  12156. return newTexture;
  12157. };
  12158. return MirrorTexture;
  12159. })(BABYLON.RenderTargetTexture);
  12160. BABYLON.MirrorTexture = MirrorTexture;
  12161. })(BABYLON || (BABYLON = {}));
  12162. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12163. var BABYLON;
  12164. (function (BABYLON) {
  12165. var DynamicTexture = (function (_super) {
  12166. __extends(DynamicTexture, _super);
  12167. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12168. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12169. _super.call(this, null, scene, !generateMipMaps);
  12170. this.name = name;
  12171. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12172. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12173. this._generateMipMaps = generateMipMaps;
  12174. if (options.getContext) {
  12175. this._canvas = options;
  12176. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12177. } else {
  12178. this._canvas = document.createElement("canvas");
  12179. if (options.width) {
  12180. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12181. } else {
  12182. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12183. }
  12184. }
  12185. var textureSize = this.getSize();
  12186. this._canvas.width = textureSize.width;
  12187. this._canvas.height = textureSize.height;
  12188. this._context = this._canvas.getContext("2d");
  12189. }
  12190. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12191. get: function () {
  12192. return true;
  12193. },
  12194. enumerable: true,
  12195. configurable: true
  12196. });
  12197. DynamicTexture.prototype.scale = function (ratio) {
  12198. var textureSize = this.getSize();
  12199. textureSize.width *= ratio;
  12200. textureSize.height *= ratio;
  12201. this._canvas.width = textureSize.width;
  12202. this._canvas.height = textureSize.height;
  12203. this.releaseInternalTexture();
  12204. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12205. };
  12206. DynamicTexture.prototype.getContext = function () {
  12207. return this._context;
  12208. };
  12209. DynamicTexture.prototype.clear = function () {
  12210. var size = this.getSize();
  12211. this._context.fillRect(0, 0, size.width, size.height);
  12212. };
  12213. DynamicTexture.prototype.update = function (invertY) {
  12214. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12215. };
  12216. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12217. if (typeof update === "undefined") { update = true; }
  12218. var size = this.getSize();
  12219. if (clearColor) {
  12220. this._context.fillStyle = clearColor;
  12221. this._context.fillRect(0, 0, size.width, size.height);
  12222. }
  12223. this._context.font = font;
  12224. if (x === null) {
  12225. var textSize = this._context.measureText(text);
  12226. x = (size.width - textSize.width) / 2;
  12227. }
  12228. this._context.fillStyle = color;
  12229. this._context.fillText(text, x, y);
  12230. if (update) {
  12231. this.update(invertY);
  12232. }
  12233. };
  12234. DynamicTexture.prototype.clone = function () {
  12235. var textureSize = this.getSize();
  12236. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12237. // Base texture
  12238. newTexture.hasAlpha = this.hasAlpha;
  12239. newTexture.level = this.level;
  12240. // Dynamic Texture
  12241. newTexture.wrapU = this.wrapU;
  12242. newTexture.wrapV = this.wrapV;
  12243. return newTexture;
  12244. };
  12245. return DynamicTexture;
  12246. })(BABYLON.Texture);
  12247. BABYLON.DynamicTexture = DynamicTexture;
  12248. })(BABYLON || (BABYLON = {}));
  12249. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12250. var BABYLON;
  12251. (function (BABYLON) {
  12252. var VideoTexture = (function (_super) {
  12253. __extends(VideoTexture, _super);
  12254. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12255. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12256. var _this = this;
  12257. _super.call(this, null, scene, !generateMipMaps, invertY);
  12258. this._autoLaunch = true;
  12259. this.name = name;
  12260. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12261. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12262. var requiredWidth = size.width || size;
  12263. var requiredHeight = size.height || size;
  12264. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12265. var textureSize = this.getSize();
  12266. this.video = document.createElement("video");
  12267. this.video.width = textureSize.width;
  12268. this.video.height = textureSize.height;
  12269. this.video.autoplay = false;
  12270. this.video.loop = true;
  12271. this.video.addEventListener("canplaythrough", function () {
  12272. if (_this._texture) {
  12273. _this._texture.isReady = true;
  12274. }
  12275. });
  12276. urls.forEach(function (url) {
  12277. var source = document.createElement("source");
  12278. source.src = url;
  12279. _this.video.appendChild(source);
  12280. });
  12281. this._lastUpdate = BABYLON.Tools.Now;
  12282. }
  12283. VideoTexture.prototype.update = function () {
  12284. if (this._autoLaunch) {
  12285. this._autoLaunch = false;
  12286. this.video.play();
  12287. }
  12288. var now = BABYLON.Tools.Now;
  12289. if (now - this._lastUpdate < 15) {
  12290. return false;
  12291. }
  12292. this._lastUpdate = now;
  12293. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12294. return true;
  12295. };
  12296. return VideoTexture;
  12297. })(BABYLON.Texture);
  12298. BABYLON.VideoTexture = VideoTexture;
  12299. })(BABYLON || (BABYLON = {}));
  12300. //# sourceMappingURL=babylon.videoTexture.js.map
  12301. var BABYLON;
  12302. (function (BABYLON) {
  12303. var EffectFallbacks = (function () {
  12304. function EffectFallbacks() {
  12305. this._defines = {};
  12306. this._currentRank = 32;
  12307. this._maxRank = -1;
  12308. }
  12309. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12310. if (!this._defines[rank]) {
  12311. if (rank < this._currentRank) {
  12312. this._currentRank = rank;
  12313. }
  12314. if (rank > this._maxRank) {
  12315. this._maxRank = rank;
  12316. }
  12317. this._defines[rank] = new Array();
  12318. }
  12319. this._defines[rank].push(define);
  12320. };
  12321. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12322. get: function () {
  12323. return this._currentRank <= this._maxRank;
  12324. },
  12325. enumerable: true,
  12326. configurable: true
  12327. });
  12328. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12329. var currentFallbacks = this._defines[this._currentRank];
  12330. for (var index = 0; index < currentFallbacks.length; index++) {
  12331. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12332. }
  12333. this._currentRank++;
  12334. return currentDefines;
  12335. };
  12336. return EffectFallbacks;
  12337. })();
  12338. BABYLON.EffectFallbacks = EffectFallbacks;
  12339. var Effect = (function () {
  12340. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12341. var _this = this;
  12342. this._isReady = false;
  12343. this._compilationError = "";
  12344. this._valueCache = [];
  12345. this._engine = engine;
  12346. this.name = baseName;
  12347. this.defines = defines;
  12348. this._uniformsNames = uniformsNames.concat(samplers);
  12349. this._samplers = samplers;
  12350. this._attributesNames = attributesNames;
  12351. this.onError = onError;
  12352. this.onCompiled = onCompiled;
  12353. var vertexSource;
  12354. var fragmentSource;
  12355. if (baseName.vertexElement) {
  12356. vertexSource = document.getElementById(baseName.vertexElement);
  12357. if (!vertexSource) {
  12358. vertexSource = baseName.vertexElement;
  12359. }
  12360. } else {
  12361. vertexSource = baseName.vertex || baseName;
  12362. }
  12363. if (baseName.fragmentElement) {
  12364. fragmentSource = document.getElementById(baseName.fragmentElement);
  12365. if (!fragmentSource) {
  12366. fragmentSource = baseName.fragmentElement;
  12367. }
  12368. } else {
  12369. fragmentSource = baseName.fragment || baseName;
  12370. }
  12371. this._loadVertexShader(vertexSource, function (vertexCode) {
  12372. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12373. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12374. });
  12375. });
  12376. }
  12377. // Properties
  12378. Effect.prototype.isReady = function () {
  12379. return this._isReady;
  12380. };
  12381. Effect.prototype.getProgram = function () {
  12382. return this._program;
  12383. };
  12384. Effect.prototype.getAttributesNames = function () {
  12385. return this._attributesNames;
  12386. };
  12387. Effect.prototype.getAttributeLocation = function (index) {
  12388. return this._attributes[index];
  12389. };
  12390. Effect.prototype.getAttributeLocationByName = function (name) {
  12391. var index = this._attributesNames.indexOf(name);
  12392. return this._attributes[index];
  12393. };
  12394. Effect.prototype.getAttributesCount = function () {
  12395. return this._attributes.length;
  12396. };
  12397. Effect.prototype.getUniformIndex = function (uniformName) {
  12398. return this._uniformsNames.indexOf(uniformName);
  12399. };
  12400. Effect.prototype.getUniform = function (uniformName) {
  12401. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12402. };
  12403. Effect.prototype.getSamplers = function () {
  12404. return this._samplers;
  12405. };
  12406. Effect.prototype.getCompilationError = function () {
  12407. return this._compilationError;
  12408. };
  12409. // Methods
  12410. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12411. // DOM element ?
  12412. if (vertex instanceof HTMLElement) {
  12413. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12414. callback(vertexCode);
  12415. return;
  12416. }
  12417. // Is in local store ?
  12418. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12419. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12420. return;
  12421. }
  12422. var vertexShaderUrl;
  12423. if (vertex[0] === ".") {
  12424. vertexShaderUrl = vertex;
  12425. } else {
  12426. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12427. }
  12428. // Vertex shader
  12429. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12430. };
  12431. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12432. // DOM element ?
  12433. if (fragment instanceof HTMLElement) {
  12434. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12435. callback(fragmentCode);
  12436. return;
  12437. }
  12438. // Is in local store ?
  12439. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12440. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12441. return;
  12442. }
  12443. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12444. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12445. return;
  12446. }
  12447. var fragmentShaderUrl;
  12448. if (fragment[0] === ".") {
  12449. fragmentShaderUrl = fragment;
  12450. } else {
  12451. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12452. }
  12453. // Fragment shader
  12454. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12455. };
  12456. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12457. try {
  12458. var engine = this._engine;
  12459. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12460. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12461. this._attributes = engine.getAttributes(this._program, attributesNames);
  12462. for (var index = 0; index < this._samplers.length; index++) {
  12463. var sampler = this.getUniform(this._samplers[index]);
  12464. if (sampler == null) {
  12465. this._samplers.splice(index, 1);
  12466. index--;
  12467. }
  12468. }
  12469. engine.bindSamplers(this);
  12470. this._isReady = true;
  12471. if (this.onCompiled) {
  12472. this.onCompiled(this);
  12473. }
  12474. } catch (e) {
  12475. // Is it a problem with precision?
  12476. if (e.message.indexOf("highp") !== -1) {
  12477. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12478. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12479. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12480. return;
  12481. }
  12482. // Let's go through fallbacks then
  12483. if (fallbacks && fallbacks.isMoreFallbacks) {
  12484. defines = fallbacks.reduce(defines);
  12485. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12486. } else {
  12487. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12488. BABYLON.Tools.Error("Defines: " + defines);
  12489. BABYLON.Tools.Error("Error: " + e.message);
  12490. this._compilationError = e.message;
  12491. if (this.onError) {
  12492. this.onError(this, this._compilationError);
  12493. }
  12494. }
  12495. }
  12496. };
  12497. Effect.prototype._bindTexture = function (channel, texture) {
  12498. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12499. };
  12500. Effect.prototype.setTexture = function (channel, texture) {
  12501. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12502. };
  12503. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12504. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12505. };
  12506. //public _cacheMatrix(uniformName, matrix) {
  12507. // if (!this._valueCache[uniformName]) {
  12508. // this._valueCache[uniformName] = new BABYLON.Matrix();
  12509. // }
  12510. // for (var index = 0; index < 16; index++) {
  12511. // this._valueCache[uniformName].m[index] = matrix.m[index];
  12512. // }
  12513. //};
  12514. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  12515. if (!this._valueCache[uniformName]) {
  12516. this._valueCache[uniformName] = [x, y];
  12517. return;
  12518. }
  12519. this._valueCache[uniformName][0] = x;
  12520. this._valueCache[uniformName][1] = y;
  12521. };
  12522. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  12523. if (!this._valueCache[uniformName]) {
  12524. this._valueCache[uniformName] = [x, y, z];
  12525. return;
  12526. }
  12527. this._valueCache[uniformName][0] = x;
  12528. this._valueCache[uniformName][1] = y;
  12529. this._valueCache[uniformName][2] = z;
  12530. };
  12531. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  12532. if (!this._valueCache[uniformName]) {
  12533. this._valueCache[uniformName] = [x, y, z, w];
  12534. return;
  12535. }
  12536. this._valueCache[uniformName][0] = x;
  12537. this._valueCache[uniformName][1] = y;
  12538. this._valueCache[uniformName][2] = z;
  12539. this._valueCache[uniformName][3] = w;
  12540. };
  12541. Effect.prototype.setArray = function (uniformName, array) {
  12542. this._engine.setArray(this.getUniform(uniformName), array);
  12543. return this;
  12544. };
  12545. Effect.prototype.setMatrices = function (uniformName, matrices) {
  12546. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  12547. return this;
  12548. };
  12549. Effect.prototype.setMatrix = function (uniformName, matrix) {
  12550. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  12551. // return;
  12552. //this._cacheMatrix(uniformName, matrix);
  12553. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  12554. return this;
  12555. };
  12556. Effect.prototype.setFloat = function (uniformName, value) {
  12557. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  12558. return this;
  12559. this._valueCache[uniformName] = value;
  12560. this._engine.setFloat(this.getUniform(uniformName), value);
  12561. return this;
  12562. };
  12563. Effect.prototype.setBool = function (uniformName, bool) {
  12564. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  12565. return this;
  12566. this._valueCache[uniformName] = bool;
  12567. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  12568. return this;
  12569. };
  12570. Effect.prototype.setVector2 = function (uniformName, vector2) {
  12571. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  12572. return this;
  12573. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  12574. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  12575. return this;
  12576. };
  12577. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  12578. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  12579. return this;
  12580. this._cacheFloat2(uniformName, x, y);
  12581. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  12582. return this;
  12583. };
  12584. Effect.prototype.setVector3 = function (uniformName, vector3) {
  12585. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  12586. return this;
  12587. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  12588. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  12589. return this;
  12590. };
  12591. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  12592. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  12593. return this;
  12594. this._cacheFloat3(uniformName, x, y, z);
  12595. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  12596. return this;
  12597. };
  12598. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  12599. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  12600. return this;
  12601. this._cacheFloat4(uniformName, x, y, z, w);
  12602. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  12603. return this;
  12604. };
  12605. Effect.prototype.setColor3 = function (uniformName, color3) {
  12606. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  12607. return this;
  12608. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  12609. this._engine.setColor3(this.getUniform(uniformName), color3);
  12610. return this;
  12611. };
  12612. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  12613. 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)
  12614. return this;
  12615. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  12616. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  12617. return this;
  12618. };
  12619. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\n vec4 leftFrag = texture2D(leftSampler, vUV);\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\n vec4 rightFrag = texture2D(textureSampler, vUV);\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  12620. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n float luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\n gl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  12621. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\n float weights[7];\n weights[0] = 0.05;\n weights[1] = 0.1;\n weights[2] = 0.2;\n weights[3] = 0.3;\n weights[4] = 0.2;\n weights[5] = 0.1;\n weights[6] = 0.05;\n\n vec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\n vec2 texelStep = texelSize * direction * blurWidth;\n vec2 start = vUV - 3.0 * texelStep;\n\n vec4 baseColor = vec4(0., 0., 0., 0.);\n vec2 texelOffset = vec2(0., 0.);\n\n for (int i = 0; i < 7; i++)\n {\n baseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\n texelOffset += texelStep;\n }\n\n gl_FragColor = baseColor;\n}",
  12622. brickPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.05;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\n if (brickColorSwitch == 0.0)\n color = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\n else if (brickColorSwitch == 2.0)\n color = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n }\n\n gl_FragColor = vec4(color, 1.0);\n}",
  12623. cloudPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\n\nuniform vec3 skyColor;\nuniform vec3 cloudColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n\n vec2 p = vUV * 12.0;\n vec3 c = mix(skyColor, cloudColor, fbm(p));\n gl_FragColor = vec4(c, 1);\n\n}",
  12624. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  12625. colorVertexShader:"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  12626. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\n vec2 onePixel = vec2(1.0, 1.0) / screenSize;\n vec4 colorSum =\n texture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\n float kernelWeight =\n kernel[0] +\n kernel[1] +\n kernel[2] +\n kernel[3] +\n kernel[4] +\n kernel[5] +\n kernel[6] +\n kernel[7] +\n kernel[8];\n\n if (kernelWeight <= 0.0) {\n kernelWeight = 1.0;\n }\n\n gl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  12627. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  12628. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\n finalWorld = finalWorld * (m0 + m1 + m2);\n#endif \n\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  12629. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(passSampler, vUV);\n}",
  12630. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\n vec3 baseColor = texture2D(textureSampler, vUV).rgb;\n vec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\n gl_FragColor = vec4(updatedColor, 1.0);\n}",
  12631. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float time;\nuniform vec3 c1;\nuniform vec3 c2;\nuniform vec3 c3;\nuniform vec3 c4;\nuniform vec3 c5;\nuniform vec3 c6;\nuniform vec2 speed;\nuniform float shift;\nuniform float alphaThreshold;\n\nvarying vec2 vUV;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n vec2 p = vUV * 8.0;\n float q = fbm(p - time * 0.1);\n vec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\n vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\n vec3 color = c * cos(shift * vUV.y);\n float luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\n gl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  12632. fxaaPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\n\nvoid main(){\n vec2 localTexelSize = texelSize;\n vec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\n vec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\n vec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\n vec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\n vec4 rgbM = texture2D(textureSampler, vUV);\n vec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n vec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\n float dirReduce = max(\n (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\n FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * localTexelSize;\n\n vec4 rgbA = 0.5 * (\n texture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\n texture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\n vec4 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(textureSampler, vUV + dir * -0.5) +\n texture2D(textureSampler, vUV + dir * 0.5));\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax)) {\n gl_FragColor = rgbA;\n }\n else {\n gl_FragColor = rgbB;\n }\n}",
  12633. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform vec3 herb1Color;\nuniform vec3 herb2Color;\nuniform vec3 herb3Color;\nuniform vec3 groundColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n vec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\n color = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\n color = mix(color, herb3Color, rand(gl_FragCoord.xy));\n color = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\n gl_FragColor = vec4(color, 1.0);\n}",
  12634. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  12635. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 textureMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  12636. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  12637. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  12638. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  12639. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 viewportMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  12640. marblePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfTilesHeight;\nuniform float numberOfTilesWidth;\nuniform float amplitude;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat turbulence(vec2 P)\n{\n float val = 0.0;\n float freq = 1.0;\n for (int i = 0; i < 4; i++)\n {\n val += abs(noise(P*freq) / freq);\n freq *= 2.07;\n }\n return val;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\n vec3 col;\n x = 0.5*(x + 1.);\n x = sqrt(x); \n x = sqrt(x);\n x = sqrt(x);\n col = vec3(.2 + .75*x); \n col.b *= 0.95; \n return col;\n}\n\nvoid main()\n{\n float brickW = 1.0 / numberOfTilesWidth;\n float brickH = 1.0 / numberOfTilesHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.01;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\n t += amplitude * turbulence(brickvUV.xy);\n t = sin(t);\n color = marble_color(t);\n }\n\n gl_FragColor = vec4(color, 0.0);\n}",
  12641. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\n vec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\n float rSq = theta.x * theta.x + theta.y * theta.y;\n vec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n return LensCenter + Scale * rvector;\n}\n\nvoid main(void)\n{\n vec2 tc = HmdWarp(vUV);\n if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n else{\n gl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n }\n}",
  12642. outlinePixelShader:"precision highp float;\n\nuniform vec4 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = color;\n}",
  12643. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\nuniform float offset;\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n vec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  12644. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n gl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  12645. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\n// Uniforms\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n float size = options.y;\n float angle = options.x;\n vec2 offset = options.zw;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n \n vColor = color;\n vUV = offset;\n\n // Clip plane\n#ifdef CLIPPLANE\n vec4 worldPos = invView * vec4(viewPos, 1.0);\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  12646. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n gl_FragColor = texture2D(textureSampler, vUV);\n}",
  12647. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  12648. proceduralVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n vPosition = position;\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  12649. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\n// Parameters\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\n float ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\n vec2 uv = vUV - vec2(0.5);\n vec2 offset = uv * depth * ref;\n vec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\n gl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  12650. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV; \nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\n vec3 color = roadColor * ratioy;\n gl_FragColor = vec4(color, 1.0);\n}",
  12651. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(254.), vec4(255.)) / vec4(254.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z / gl_FragCoord.w;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  12652. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  12653. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n if (alphaTest) \n {\n if (baseColor.a < 0.95)\n discard;\n }\n\n baseColor *= vColor;\n\n#ifdef FOG\n float fog = CalcFogFactor();\n baseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = baseColor;\n}",
  12654. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\n// Uniforms\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n \n float angle = options.x;\n float size = options.y;\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n\n // Color\n vColor = color;\n \n // Texture\n vec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\n vUV = (uvOffset + cellInfo.zw) * uvScale;\n\n // Fog\n#ifdef FOG\n fFogDistance = viewPos.z;\n#endif\n}",
  12655. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float ampScale;\nuniform vec3 woodColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\n vec3 wood = woodColor * ratioy;\n gl_FragColor = vec4(wood, 1.0);\n}",
  12656. };
  12657. return Effect;
  12658. })();
  12659. BABYLON.Effect = Effect;
  12660. })(BABYLON || (BABYLON = {}));
  12661. //# sourceMappingURL=babylon.effect.js.map
  12662. var BABYLON;
  12663. (function (BABYLON) {
  12664. var Material = (function () {
  12665. function Material(name, scene, doNotAdd) {
  12666. this.name = name;
  12667. this.checkReadyOnEveryCall = true;
  12668. this.checkReadyOnlyOnce = false;
  12669. this.state = "";
  12670. this.alpha = 1.0;
  12671. this.backFaceCulling = true;
  12672. this._wasPreviouslyReady = false;
  12673. this._fillMode = Material.TriangleFillMode;
  12674. this.pointSize = 1.0;
  12675. this.id = name;
  12676. this._scene = scene;
  12677. if (!doNotAdd) {
  12678. scene.materials.push(this);
  12679. }
  12680. }
  12681. Object.defineProperty(Material, "TriangleFillMode", {
  12682. get: function () {
  12683. return Material._TriangleFillMode;
  12684. },
  12685. enumerable: true,
  12686. configurable: true
  12687. });
  12688. Object.defineProperty(Material, "WireFrameFillMode", {
  12689. get: function () {
  12690. return Material._WireFrameFillMode;
  12691. },
  12692. enumerable: true,
  12693. configurable: true
  12694. });
  12695. Object.defineProperty(Material, "PointFillMode", {
  12696. get: function () {
  12697. return Material._PointFillMode;
  12698. },
  12699. enumerable: true,
  12700. configurable: true
  12701. });
  12702. Object.defineProperty(Material.prototype, "wireframe", {
  12703. get: function () {
  12704. return this._fillMode === Material.WireFrameFillMode;
  12705. },
  12706. set: function (value) {
  12707. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  12708. },
  12709. enumerable: true,
  12710. configurable: true
  12711. });
  12712. Object.defineProperty(Material.prototype, "pointsCloud", {
  12713. get: function () {
  12714. return this._fillMode === Material.PointFillMode;
  12715. },
  12716. set: function (value) {
  12717. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  12718. },
  12719. enumerable: true,
  12720. configurable: true
  12721. });
  12722. Object.defineProperty(Material.prototype, "fillMode", {
  12723. get: function () {
  12724. return this._fillMode;
  12725. },
  12726. set: function (value) {
  12727. this._fillMode = value;
  12728. },
  12729. enumerable: true,
  12730. configurable: true
  12731. });
  12732. Material.prototype.isReady = function (mesh, useInstances) {
  12733. return true;
  12734. };
  12735. Material.prototype.getEffect = function () {
  12736. return this._effect;
  12737. };
  12738. Material.prototype.getScene = function () {
  12739. return this._scene;
  12740. };
  12741. Material.prototype.needAlphaBlending = function () {
  12742. return (this.alpha < 1.0);
  12743. };
  12744. Material.prototype.needAlphaTesting = function () {
  12745. return false;
  12746. };
  12747. Material.prototype.getAlphaTestTexture = function () {
  12748. return null;
  12749. };
  12750. Material.prototype.trackCreation = function (onCompiled, onError) {
  12751. };
  12752. Material.prototype._preBind = function () {
  12753. var engine = this._scene.getEngine();
  12754. engine.enableEffect(this._effect);
  12755. engine.setState(this.backFaceCulling);
  12756. };
  12757. Material.prototype.bind = function (world, mesh) {
  12758. this._scene._cachedMaterial = this;
  12759. if (this.onBind) {
  12760. this.onBind(this);
  12761. }
  12762. };
  12763. Material.prototype.bindOnlyWorldMatrix = function (world) {
  12764. };
  12765. Material.prototype.unbind = function () {
  12766. };
  12767. Material.prototype.dispose = function (forceDisposeEffect) {
  12768. // Remove from scene
  12769. var index = this._scene.materials.indexOf(this);
  12770. this._scene.materials.splice(index, 1);
  12771. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  12772. if (forceDisposeEffect && this._effect) {
  12773. this._scene.getEngine()._releaseEffect(this._effect);
  12774. this._effect = null;
  12775. }
  12776. // Callback
  12777. if (this.onDispose) {
  12778. this.onDispose();
  12779. }
  12780. };
  12781. Material._TriangleFillMode = 0;
  12782. Material._WireFrameFillMode = 1;
  12783. Material._PointFillMode = 2;
  12784. return Material;
  12785. })();
  12786. BABYLON.Material = Material;
  12787. })(BABYLON || (BABYLON = {}));
  12788. //# sourceMappingURL=babylon.material.js.map
  12789. var BABYLON;
  12790. (function (BABYLON) {
  12791. var maxSimultaneousLights = 4;
  12792. var FresnelParameters = (function () {
  12793. function FresnelParameters() {
  12794. this.isEnabled = true;
  12795. this.leftColor = BABYLON.Color3.White();
  12796. this.rightColor = BABYLON.Color3.Black();
  12797. this.bias = 0;
  12798. this.power = 1;
  12799. }
  12800. return FresnelParameters;
  12801. })();
  12802. BABYLON.FresnelParameters = FresnelParameters;
  12803. var StandardMaterial = (function (_super) {
  12804. __extends(StandardMaterial, _super);
  12805. function StandardMaterial(name, scene) {
  12806. var _this = this;
  12807. _super.call(this, name, scene);
  12808. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12809. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  12810. this.specularColor = new BABYLON.Color3(1, 1, 1);
  12811. this.specularPower = 64;
  12812. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  12813. this.useAlphaFromDiffuseTexture = false;
  12814. this.useSpecularOverAlpha = true;
  12815. this.fogEnabled = true;
  12816. this._cachedDefines = null;
  12817. this._renderTargets = new BABYLON.SmartArray(16);
  12818. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  12819. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  12820. this._scaledDiffuse = new BABYLON.Color3();
  12821. this._scaledSpecular = new BABYLON.Color3();
  12822. this.getRenderTargetTextures = function () {
  12823. _this._renderTargets.reset();
  12824. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  12825. _this._renderTargets.push(_this.reflectionTexture);
  12826. }
  12827. return _this._renderTargets;
  12828. };
  12829. }
  12830. StandardMaterial.prototype.needAlphaBlending = function () {
  12831. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  12832. };
  12833. StandardMaterial.prototype.needAlphaTesting = function () {
  12834. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  12835. };
  12836. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  12837. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  12838. };
  12839. StandardMaterial.prototype.getAlphaTestTexture = function () {
  12840. return this.diffuseTexture;
  12841. };
  12842. // Methods
  12843. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  12844. if (this.checkReadyOnlyOnce) {
  12845. if (this._wasPreviouslyReady) {
  12846. return true;
  12847. }
  12848. }
  12849. var scene = this.getScene();
  12850. if (!this.checkReadyOnEveryCall) {
  12851. if (this._renderId === scene.getRenderId()) {
  12852. return true;
  12853. }
  12854. }
  12855. var engine = scene.getEngine();
  12856. var defines = [];
  12857. var fallbacks = new BABYLON.EffectFallbacks();
  12858. // Textures
  12859. if (scene.texturesEnabled) {
  12860. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12861. if (!this.diffuseTexture.isReady()) {
  12862. return false;
  12863. } else {
  12864. defines.push("#define DIFFUSE");
  12865. }
  12866. }
  12867. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12868. if (!this.ambientTexture.isReady()) {
  12869. return false;
  12870. } else {
  12871. defines.push("#define AMBIENT");
  12872. }
  12873. }
  12874. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12875. if (!this.opacityTexture.isReady()) {
  12876. return false;
  12877. } else {
  12878. defines.push("#define OPACITY");
  12879. if (this.opacityTexture.getAlphaFromRGB) {
  12880. defines.push("#define OPACITYRGB");
  12881. }
  12882. }
  12883. }
  12884. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12885. if (!this.reflectionTexture.isReady()) {
  12886. return false;
  12887. } else {
  12888. defines.push("#define REFLECTION");
  12889. fallbacks.addFallback(0, "REFLECTION");
  12890. }
  12891. }
  12892. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12893. if (!this.emissiveTexture.isReady()) {
  12894. return false;
  12895. } else {
  12896. defines.push("#define EMISSIVE");
  12897. }
  12898. }
  12899. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12900. if (!this.specularTexture.isReady()) {
  12901. return false;
  12902. } else {
  12903. defines.push("#define SPECULAR");
  12904. fallbacks.addFallback(0, "SPECULAR");
  12905. }
  12906. }
  12907. }
  12908. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  12909. if (!this.bumpTexture.isReady()) {
  12910. return false;
  12911. } else {
  12912. defines.push("#define BUMP");
  12913. fallbacks.addFallback(0, "BUMP");
  12914. }
  12915. }
  12916. // Effect
  12917. if (this.useSpecularOverAlpha) {
  12918. defines.push("#define SPECULAROVERALPHA");
  12919. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  12920. }
  12921. if (scene.clipPlane) {
  12922. defines.push("#define CLIPPLANE");
  12923. }
  12924. if (engine.getAlphaTesting()) {
  12925. defines.push("#define ALPHATEST");
  12926. }
  12927. if (this._shouldUseAlphaFromDiffuseTexture()) {
  12928. defines.push("#define ALPHAFROMDIFFUSE");
  12929. }
  12930. // Point size
  12931. if (this.pointsCloud || scene.forcePointsCloud) {
  12932. defines.push("#define POINTSIZE");
  12933. }
  12934. // Fog
  12935. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12936. defines.push("#define FOG");
  12937. fallbacks.addFallback(1, "FOG");
  12938. }
  12939. var shadowsActivated = false;
  12940. var lightIndex = 0;
  12941. if (scene.lightsEnabled) {
  12942. for (var index = 0; index < scene.lights.length; index++) {
  12943. var light = scene.lights[index];
  12944. if (!light.isEnabled()) {
  12945. continue;
  12946. }
  12947. // Excluded check
  12948. if (light._excludedMeshesIds.length > 0) {
  12949. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  12950. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  12951. if (excludedMesh) {
  12952. light.excludedMeshes.push(excludedMesh);
  12953. }
  12954. }
  12955. light._excludedMeshesIds = [];
  12956. }
  12957. // Included check
  12958. if (light._includedOnlyMeshesIds.length > 0) {
  12959. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  12960. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  12961. if (includedOnlyMesh) {
  12962. light.includedOnlyMeshes.push(includedOnlyMesh);
  12963. }
  12964. }
  12965. light._includedOnlyMeshesIds = [];
  12966. }
  12967. if (!light.canAffectMesh(mesh)) {
  12968. continue;
  12969. }
  12970. defines.push("#define LIGHT" + lightIndex);
  12971. if (lightIndex > 0) {
  12972. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  12973. }
  12974. var type;
  12975. if (light instanceof BABYLON.SpotLight) {
  12976. type = "#define SPOTLIGHT" + lightIndex;
  12977. } else if (light instanceof BABYLON.HemisphericLight) {
  12978. type = "#define HEMILIGHT" + lightIndex;
  12979. } else {
  12980. type = "#define POINTDIRLIGHT" + lightIndex;
  12981. }
  12982. defines.push(type);
  12983. if (lightIndex > 0) {
  12984. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  12985. }
  12986. // Shadows
  12987. if (scene.shadowsEnabled) {
  12988. var shadowGenerator = light.getShadowGenerator();
  12989. if (mesh && mesh.receiveShadows && shadowGenerator) {
  12990. defines.push("#define SHADOW" + lightIndex);
  12991. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  12992. if (!shadowsActivated) {
  12993. defines.push("#define SHADOWS");
  12994. shadowsActivated = true;
  12995. }
  12996. if (shadowGenerator.useVarianceShadowMap) {
  12997. defines.push("#define SHADOWVSM" + lightIndex);
  12998. if (lightIndex > 0) {
  12999. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13000. }
  13001. }
  13002. if (shadowGenerator.usePoissonSampling) {
  13003. defines.push("#define SHADOWPCF" + lightIndex);
  13004. if (lightIndex > 0) {
  13005. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13006. }
  13007. }
  13008. }
  13009. }
  13010. lightIndex++;
  13011. if (lightIndex === maxSimultaneousLights)
  13012. break;
  13013. }
  13014. }
  13015. if (StandardMaterial.FresnelEnabled) {
  13016. // Fresnel
  13017. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13018. var fresnelRank = 1;
  13019. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13020. defines.push("#define DIFFUSEFRESNEL");
  13021. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13022. fresnelRank++;
  13023. }
  13024. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13025. defines.push("#define OPACITYFRESNEL");
  13026. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13027. fresnelRank++;
  13028. }
  13029. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13030. defines.push("#define REFLECTIONFRESNEL");
  13031. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13032. fresnelRank++;
  13033. }
  13034. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13035. defines.push("#define EMISSIVEFRESNEL");
  13036. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13037. fresnelRank++;
  13038. }
  13039. defines.push("#define FRESNEL");
  13040. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13041. }
  13042. }
  13043. // Attribs
  13044. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13045. if (mesh) {
  13046. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13047. attribs.push(BABYLON.VertexBuffer.UVKind);
  13048. defines.push("#define UV1");
  13049. }
  13050. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13051. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13052. defines.push("#define UV2");
  13053. }
  13054. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13055. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13056. defines.push("#define VERTEXCOLOR");
  13057. if (mesh.hasVertexAlpha) {
  13058. defines.push("#define VERTEXALPHA");
  13059. }
  13060. }
  13061. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13062. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13063. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13064. defines.push("#define BONES");
  13065. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13066. defines.push("#define BONES4");
  13067. fallbacks.addFallback(0, "BONES4");
  13068. }
  13069. // Instances
  13070. if (useInstances) {
  13071. defines.push("#define INSTANCES");
  13072. attribs.push("world0");
  13073. attribs.push("world1");
  13074. attribs.push("world2");
  13075. attribs.push("world3");
  13076. }
  13077. }
  13078. // Get correct effect
  13079. var join = defines.join("\n");
  13080. if (this._cachedDefines !== join) {
  13081. this._cachedDefines = join;
  13082. scene.resetCachedMaterial();
  13083. // Legacy browser patch
  13084. var shaderName = "default";
  13085. if (!scene.getEngine().getCaps().standardDerivatives) {
  13086. shaderName = "legacydefault";
  13087. }
  13088. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  13089. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  13090. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  13091. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  13092. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  13093. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  13094. "vFogInfos", "vFogColor", "pointSize",
  13095. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  13096. "mBones",
  13097. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  13098. "darkness0", "darkness1", "darkness2", "darkness3",
  13099. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  13100. ], [
  13101. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  13102. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  13103. ], join, fallbacks, this.onCompiled, this.onError);
  13104. }
  13105. if (!this._effect.isReady()) {
  13106. return false;
  13107. }
  13108. this._renderId = scene.getRenderId();
  13109. this._wasPreviouslyReady = true;
  13110. return true;
  13111. };
  13112. StandardMaterial.prototype.unbind = function () {
  13113. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13114. this._effect.setTexture("reflection2DSampler", null);
  13115. }
  13116. };
  13117. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13118. this._effect.setMatrix("world", world);
  13119. };
  13120. StandardMaterial.prototype.bind = function (world, mesh) {
  13121. var scene = this.getScene();
  13122. // Matrices
  13123. this.bindOnlyWorldMatrix(world);
  13124. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13125. // Bones
  13126. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13127. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13128. }
  13129. if (scene.getCachedMaterial() !== this) {
  13130. if (StandardMaterial.FresnelEnabled) {
  13131. // Fresnel
  13132. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13133. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13134. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13135. }
  13136. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13137. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13138. }
  13139. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13140. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13141. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13142. }
  13143. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13144. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13145. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13146. }
  13147. }
  13148. // Textures
  13149. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13150. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13151. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13152. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13153. }
  13154. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13155. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13156. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13157. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13158. }
  13159. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13160. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13161. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13162. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13163. }
  13164. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13165. if (this.reflectionTexture.isCube) {
  13166. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13167. } else {
  13168. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13169. }
  13170. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13171. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13172. }
  13173. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13174. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13175. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13176. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13177. }
  13178. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13179. this._effect.setTexture("specularSampler", this.specularTexture);
  13180. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13181. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13182. }
  13183. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13184. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13185. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13186. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13187. }
  13188. // Clip plane
  13189. if (scene.clipPlane) {
  13190. var clipPlane = scene.clipPlane;
  13191. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13192. }
  13193. // Point size
  13194. if (this.pointsCloud) {
  13195. this._effect.setFloat("pointSize", this.pointSize);
  13196. }
  13197. // Colors
  13198. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13199. // Scaling down color according to emissive
  13200. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13201. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13202. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13203. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13204. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13205. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13206. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13207. }
  13208. // Scaling down color according to emissive
  13209. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13210. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13211. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13212. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13213. if (scene.lightsEnabled) {
  13214. var lightIndex = 0;
  13215. for (var index = 0; index < scene.lights.length; index++) {
  13216. var light = scene.lights[index];
  13217. if (!light.isEnabled()) {
  13218. continue;
  13219. }
  13220. if (!light.canAffectMesh(mesh)) {
  13221. continue;
  13222. }
  13223. if (light instanceof BABYLON.PointLight) {
  13224. // Point Light
  13225. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13226. } else if (light instanceof BABYLON.DirectionalLight) {
  13227. // Directional Light
  13228. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13229. } else if (light instanceof BABYLON.SpotLight) {
  13230. // Spot Light
  13231. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13232. } else if (light instanceof BABYLON.HemisphericLight) {
  13233. // Hemispheric Light
  13234. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13235. }
  13236. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13237. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13238. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13239. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13240. // Shadows
  13241. if (scene.shadowsEnabled) {
  13242. var shadowGenerator = light.getShadowGenerator();
  13243. if (mesh.receiveShadows && shadowGenerator) {
  13244. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13245. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13246. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13247. }
  13248. }
  13249. lightIndex++;
  13250. if (lightIndex === maxSimultaneousLights)
  13251. break;
  13252. }
  13253. }
  13254. // View
  13255. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13256. this._effect.setMatrix("view", scene.getViewMatrix());
  13257. }
  13258. // Fog
  13259. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13260. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13261. this._effect.setColor3("vFogColor", scene.fogColor);
  13262. }
  13263. _super.prototype.bind.call(this, world, mesh);
  13264. };
  13265. StandardMaterial.prototype.getAnimatables = function () {
  13266. var results = [];
  13267. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13268. results.push(this.diffuseTexture);
  13269. }
  13270. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13271. results.push(this.ambientTexture);
  13272. }
  13273. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13274. results.push(this.opacityTexture);
  13275. }
  13276. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13277. results.push(this.reflectionTexture);
  13278. }
  13279. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13280. results.push(this.emissiveTexture);
  13281. }
  13282. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13283. results.push(this.specularTexture);
  13284. }
  13285. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13286. results.push(this.bumpTexture);
  13287. }
  13288. return results;
  13289. };
  13290. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13291. if (this.diffuseTexture) {
  13292. this.diffuseTexture.dispose();
  13293. }
  13294. if (this.ambientTexture) {
  13295. this.ambientTexture.dispose();
  13296. }
  13297. if (this.opacityTexture) {
  13298. this.opacityTexture.dispose();
  13299. }
  13300. if (this.reflectionTexture) {
  13301. this.reflectionTexture.dispose();
  13302. }
  13303. if (this.emissiveTexture) {
  13304. this.emissiveTexture.dispose();
  13305. }
  13306. if (this.specularTexture) {
  13307. this.specularTexture.dispose();
  13308. }
  13309. if (this.bumpTexture) {
  13310. this.bumpTexture.dispose();
  13311. }
  13312. _super.prototype.dispose.call(this, forceDisposeEffect);
  13313. };
  13314. StandardMaterial.prototype.clone = function (name) {
  13315. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13316. // Base material
  13317. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13318. newStandardMaterial.alpha = this.alpha;
  13319. newStandardMaterial.fillMode = this.fillMode;
  13320. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13321. // Standard material
  13322. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13323. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13324. }
  13325. if (this.ambientTexture && this.ambientTexture.clone) {
  13326. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13327. }
  13328. if (this.opacityTexture && this.opacityTexture.clone) {
  13329. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13330. }
  13331. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13332. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13333. }
  13334. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13335. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13336. }
  13337. if (this.specularTexture && this.specularTexture.clone) {
  13338. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13339. }
  13340. if (this.bumpTexture && this.bumpTexture.clone) {
  13341. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13342. }
  13343. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13344. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13345. newStandardMaterial.specularColor = this.specularColor.clone();
  13346. newStandardMaterial.specularPower = this.specularPower;
  13347. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13348. return newStandardMaterial;
  13349. };
  13350. StandardMaterial.DiffuseTextureEnabled = true;
  13351. StandardMaterial.AmbientTextureEnabled = true;
  13352. StandardMaterial.OpacityTextureEnabled = true;
  13353. StandardMaterial.ReflectionTextureEnabled = true;
  13354. StandardMaterial.EmissiveTextureEnabled = true;
  13355. StandardMaterial.SpecularTextureEnabled = true;
  13356. StandardMaterial.BumpTextureEnabled = true;
  13357. StandardMaterial.FresnelEnabled = true;
  13358. return StandardMaterial;
  13359. })(BABYLON.Material);
  13360. BABYLON.StandardMaterial = StandardMaterial;
  13361. })(BABYLON || (BABYLON = {}));
  13362. //# sourceMappingURL=babylon.standardMaterial.js.map
  13363. var BABYLON;
  13364. (function (BABYLON) {
  13365. var MultiMaterial = (function (_super) {
  13366. __extends(MultiMaterial, _super);
  13367. function MultiMaterial(name, scene) {
  13368. _super.call(this, name, scene, true);
  13369. this.subMaterials = new Array();
  13370. scene.multiMaterials.push(this);
  13371. }
  13372. // Properties
  13373. MultiMaterial.prototype.getSubMaterial = function (index) {
  13374. if (index < 0 || index >= this.subMaterials.length) {
  13375. return this.getScene().defaultMaterial;
  13376. }
  13377. return this.subMaterials[index];
  13378. };
  13379. // Methods
  13380. MultiMaterial.prototype.isReady = function (mesh) {
  13381. for (var index = 0; index < this.subMaterials.length; index++) {
  13382. var subMaterial = this.subMaterials[index];
  13383. if (subMaterial) {
  13384. if (!this.subMaterials[index].isReady(mesh)) {
  13385. return false;
  13386. }
  13387. }
  13388. }
  13389. return true;
  13390. };
  13391. return MultiMaterial;
  13392. })(BABYLON.Material);
  13393. BABYLON.MultiMaterial = MultiMaterial;
  13394. })(BABYLON || (BABYLON = {}));
  13395. //# sourceMappingURL=babylon.multiMaterial.js.map
  13396. var BABYLON;
  13397. (function (BABYLON) {
  13398. var Database = (function () {
  13399. function Database(urlToScene, callbackManifestChecked) {
  13400. // Handling various flavors of prefixed version of IndexedDB
  13401. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13402. this.callbackManifestChecked = callbackManifestChecked;
  13403. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13404. this.db = null;
  13405. this.enableSceneOffline = false;
  13406. this.enableTexturesOffline = false;
  13407. this.manifestVersionFound = 0;
  13408. this.mustUpdateRessources = false;
  13409. this.hasReachedQuota = false;
  13410. this.checkManifestFile();
  13411. }
  13412. Database.prototype.checkManifestFile = function () {
  13413. var _this = this;
  13414. function noManifestFile() {
  13415. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13416. that.enableSceneOffline = false;
  13417. that.enableTexturesOffline = false;
  13418. that.callbackManifestChecked(false);
  13419. }
  13420. var that = this;
  13421. var manifestURL = this.currentSceneUrl + ".manifest";
  13422. var xhr = new XMLHttpRequest();
  13423. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13424. xhr.open("GET", manifestURLTimeStamped, true);
  13425. xhr.addEventListener("load", function () {
  13426. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13427. try {
  13428. var manifestFile = JSON.parse(xhr.response);
  13429. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13430. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13431. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13432. _this.manifestVersionFound = manifestFile.version;
  13433. }
  13434. if (_this.callbackManifestChecked) {
  13435. _this.callbackManifestChecked(true);
  13436. }
  13437. } catch (ex) {
  13438. noManifestFile();
  13439. }
  13440. } else {
  13441. noManifestFile();
  13442. }
  13443. }, false);
  13444. xhr.addEventListener("error", function (event) {
  13445. noManifestFile();
  13446. }, false);
  13447. try {
  13448. xhr.send();
  13449. } catch (ex) {
  13450. BABYLON.Tools.Error("Error on XHR send request.");
  13451. that.callbackManifestChecked(false);
  13452. }
  13453. };
  13454. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13455. var _this = this;
  13456. function handleError() {
  13457. that.isSupported = false;
  13458. if (errorCallback)
  13459. errorCallback();
  13460. }
  13461. var that = this;
  13462. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13463. // Your browser doesn't support IndexedDB
  13464. this.isSupported = false;
  13465. if (errorCallback)
  13466. errorCallback();
  13467. } else {
  13468. // If the DB hasn't been opened or created yet
  13469. if (!this.db) {
  13470. this.hasReachedQuota = false;
  13471. this.isSupported = true;
  13472. var request = this.idbFactory.open("babylonjs", 1);
  13473. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13474. request.onerror = function (event) {
  13475. handleError();
  13476. };
  13477. // executes when a version change transaction cannot complete due to other active transactions
  13478. request.onblocked = function (event) {
  13479. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13480. handleError();
  13481. };
  13482. // DB has been opened successfully
  13483. request.onsuccess = function (event) {
  13484. _this.db = request.result;
  13485. successCallback();
  13486. };
  13487. // Initialization of the DB. Creating Scenes & Textures stores
  13488. request.onupgradeneeded = function (event) {
  13489. _this.db = (event.target).result;
  13490. try {
  13491. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13492. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13493. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13494. } catch (ex) {
  13495. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13496. handleError();
  13497. }
  13498. };
  13499. } else {
  13500. if (successCallback)
  13501. successCallback();
  13502. }
  13503. }
  13504. };
  13505. Database.prototype.loadImageFromDB = function (url, image) {
  13506. var _this = this;
  13507. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  13508. var saveAndLoadImage = function () {
  13509. if (!_this.hasReachedQuota && _this.db !== null) {
  13510. // the texture is not yet in the DB, let's try to save it
  13511. _this._saveImageIntoDBAsync(completeURL, image);
  13512. } else {
  13513. image.src = url;
  13514. }
  13515. };
  13516. if (!this.mustUpdateRessources) {
  13517. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  13518. } else {
  13519. saveAndLoadImage();
  13520. }
  13521. };
  13522. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  13523. if (this.isSupported && this.db !== null) {
  13524. var texture;
  13525. var transaction = this.db.transaction(["textures"]);
  13526. transaction.onabort = function (event) {
  13527. image.src = url;
  13528. };
  13529. transaction.oncomplete = function (event) {
  13530. var blobTextureURL;
  13531. if (texture) {
  13532. var URL = window.URL || window.webkitURL;
  13533. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  13534. image.onerror = function () {
  13535. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  13536. image.src = url;
  13537. };
  13538. image.src = blobTextureURL;
  13539. } else {
  13540. notInDBCallback();
  13541. }
  13542. };
  13543. var getRequest = transaction.objectStore("textures").get(url);
  13544. getRequest.onsuccess = function (event) {
  13545. texture = (event.target).result;
  13546. };
  13547. getRequest.onerror = function (event) {
  13548. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  13549. image.src = url;
  13550. };
  13551. } else {
  13552. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13553. image.src = url;
  13554. }
  13555. };
  13556. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  13557. var _this = this;
  13558. if (this.isSupported) {
  13559. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  13560. var generateBlobUrl = function () {
  13561. var blobTextureURL;
  13562. if (blob) {
  13563. var URL = window.URL || window.webkitURL;
  13564. try {
  13565. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  13566. } catch (ex) {
  13567. blobTextureURL = URL.createObjectURL(blob);
  13568. }
  13569. }
  13570. image.src = blobTextureURL;
  13571. };
  13572. if (BABYLON.Database.isUASupportingBlobStorage) {
  13573. var xhr = new XMLHttpRequest(), blob;
  13574. xhr.open("GET", url, true);
  13575. xhr.responseType = "blob";
  13576. xhr.addEventListener("load", function () {
  13577. if (xhr.status === 200) {
  13578. // Blob as response (XHR2)
  13579. blob = xhr.response;
  13580. var transaction = _this.db.transaction(["textures"], "readwrite");
  13581. // the transaction could abort because of a QuotaExceededError error
  13582. transaction.onabort = function (event) {
  13583. try {
  13584. if (event.srcElement.error.name === "QuotaExceededError") {
  13585. this.hasReachedQuota = true;
  13586. }
  13587. } catch (ex) {
  13588. }
  13589. generateBlobUrl();
  13590. };
  13591. transaction.oncomplete = function (event) {
  13592. generateBlobUrl();
  13593. };
  13594. var newTexture = { textureUrl: url, data: blob };
  13595. try {
  13596. // Put the blob into the dabase
  13597. var addRequest = transaction.objectStore("textures").put(newTexture);
  13598. addRequest.onsuccess = function (event) {
  13599. };
  13600. addRequest.onerror = function (event) {
  13601. generateBlobUrl();
  13602. };
  13603. } catch (ex) {
  13604. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  13605. if (ex.code === 25) {
  13606. BABYLON.Database.isUASupportingBlobStorage = false;
  13607. }
  13608. image.src = url;
  13609. }
  13610. } else {
  13611. image.src = url;
  13612. }
  13613. }, false);
  13614. xhr.addEventListener("error", function (event) {
  13615. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  13616. image.src = url;
  13617. }, false);
  13618. xhr.send();
  13619. } else {
  13620. image.src = url;
  13621. }
  13622. } else {
  13623. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13624. image.src = url;
  13625. }
  13626. };
  13627. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  13628. var _this = this;
  13629. var updateVersion = function (event) {
  13630. // the version is not yet in the DB or we need to update it
  13631. _this._saveVersionIntoDBAsync(url, versionLoaded);
  13632. };
  13633. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  13634. };
  13635. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  13636. var _this = this;
  13637. if (this.isSupported) {
  13638. var version;
  13639. try {
  13640. var transaction = this.db.transaction(["versions"]);
  13641. transaction.oncomplete = function (event) {
  13642. if (version) {
  13643. // If the version in the JSON file is > than the version in DB
  13644. if (_this.manifestVersionFound > version.data) {
  13645. _this.mustUpdateRessources = true;
  13646. updateInDBCallback();
  13647. } else {
  13648. callback(version.data);
  13649. }
  13650. } else {
  13651. _this.mustUpdateRessources = true;
  13652. updateInDBCallback();
  13653. }
  13654. };
  13655. transaction.onabort = function (event) {
  13656. callback(-1);
  13657. };
  13658. var getRequest = transaction.objectStore("versions").get(url);
  13659. getRequest.onsuccess = function (event) {
  13660. version = (event.target).result;
  13661. };
  13662. getRequest.onerror = function (event) {
  13663. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  13664. callback(-1);
  13665. };
  13666. } catch (ex) {
  13667. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  13668. callback(-1);
  13669. }
  13670. } else {
  13671. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13672. callback(-1);
  13673. }
  13674. };
  13675. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  13676. var _this = this;
  13677. if (this.isSupported && !this.hasReachedQuota) {
  13678. try {
  13679. // Open a transaction to the database
  13680. var transaction = this.db.transaction(["versions"], "readwrite");
  13681. // the transaction could abort because of a QuotaExceededError error
  13682. transaction.onabort = function (event) {
  13683. try {
  13684. if (event.srcElement.error.name === "QuotaExceededError") {
  13685. _this.hasReachedQuota = true;
  13686. }
  13687. } catch (ex) {
  13688. }
  13689. callback(-1);
  13690. };
  13691. transaction.oncomplete = function (event) {
  13692. callback(_this.manifestVersionFound);
  13693. };
  13694. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  13695. // Put the scene into the database
  13696. var addRequest = transaction.objectStore("versions").put(newVersion);
  13697. addRequest.onsuccess = function (event) {
  13698. };
  13699. addRequest.onerror = function (event) {
  13700. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  13701. };
  13702. } catch (ex) {
  13703. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  13704. callback(-1);
  13705. }
  13706. } else {
  13707. callback(-1);
  13708. }
  13709. };
  13710. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  13711. var _this = this;
  13712. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  13713. var saveAndLoadFile = function (event) {
  13714. // the scene is not yet in the DB, let's try to save it
  13715. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  13716. };
  13717. this._checkVersionFromDB(completeUrl, function (version) {
  13718. if (version !== -1) {
  13719. if (!_this.mustUpdateRessources) {
  13720. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  13721. } else {
  13722. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  13723. }
  13724. } else {
  13725. errorCallback();
  13726. }
  13727. });
  13728. };
  13729. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  13730. if (this.isSupported) {
  13731. var targetStore;
  13732. if (url.indexOf(".babylon") !== -1) {
  13733. targetStore = "scenes";
  13734. } else {
  13735. targetStore = "textures";
  13736. }
  13737. var file;
  13738. var transaction = this.db.transaction([targetStore]);
  13739. transaction.oncomplete = function (event) {
  13740. if (file) {
  13741. callback(file.data);
  13742. } else {
  13743. notInDBCallback();
  13744. }
  13745. };
  13746. transaction.onabort = function (event) {
  13747. notInDBCallback();
  13748. };
  13749. var getRequest = transaction.objectStore(targetStore).get(url);
  13750. getRequest.onsuccess = function (event) {
  13751. file = (event.target).result;
  13752. };
  13753. getRequest.onerror = function (event) {
  13754. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  13755. notInDBCallback();
  13756. };
  13757. } else {
  13758. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13759. callback();
  13760. }
  13761. };
  13762. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  13763. var _this = this;
  13764. if (this.isSupported) {
  13765. var targetStore;
  13766. if (url.indexOf(".babylon") !== -1) {
  13767. targetStore = "scenes";
  13768. } else {
  13769. targetStore = "textures";
  13770. }
  13771. // Create XHR
  13772. var xhr = new XMLHttpRequest(), fileData;
  13773. xhr.open("GET", url, true);
  13774. if (useArrayBuffer) {
  13775. xhr.responseType = "arraybuffer";
  13776. }
  13777. xhr.onprogress = progressCallback;
  13778. xhr.addEventListener("load", function () {
  13779. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  13780. // Blob as response (XHR2)
  13781. //fileData = xhr.responseText;
  13782. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  13783. if (!_this.hasReachedQuota) {
  13784. // Open a transaction to the database
  13785. var transaction = _this.db.transaction([targetStore], "readwrite");
  13786. // the transaction could abort because of a QuotaExceededError error
  13787. transaction.onabort = function (event) {
  13788. try {
  13789. if (event.srcElement.error.name === "QuotaExceededError") {
  13790. this.hasReachedQuota = true;
  13791. }
  13792. } catch (ex) {
  13793. }
  13794. callback(fileData);
  13795. };
  13796. transaction.oncomplete = function (event) {
  13797. callback(fileData);
  13798. };
  13799. var newFile;
  13800. if (targetStore === "scenes") {
  13801. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  13802. } else {
  13803. newFile = { textureUrl: url, data: fileData };
  13804. }
  13805. try {
  13806. // Put the scene into the database
  13807. var addRequest = transaction.objectStore(targetStore).put(newFile);
  13808. addRequest.onsuccess = function (event) {
  13809. };
  13810. addRequest.onerror = function (event) {
  13811. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  13812. };
  13813. } catch (ex) {
  13814. callback(fileData);
  13815. }
  13816. } else {
  13817. callback(fileData);
  13818. }
  13819. } else {
  13820. callback();
  13821. }
  13822. }, false);
  13823. xhr.addEventListener("error", function (event) {
  13824. BABYLON.Tools.Error("error on XHR request.");
  13825. callback();
  13826. }, false);
  13827. xhr.send();
  13828. } else {
  13829. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13830. callback();
  13831. }
  13832. };
  13833. Database.isUASupportingBlobStorage = true;
  13834. Database.parseURL = function (url) {
  13835. var a = document.createElement('a');
  13836. a.href = url;
  13837. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  13838. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  13839. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  13840. return absLocation;
  13841. };
  13842. Database.ReturnFullUrlLocation = function (url) {
  13843. if (url.indexOf("http:/") === -1) {
  13844. return (BABYLON.Database.parseURL(window.location.href) + url);
  13845. } else {
  13846. return url;
  13847. }
  13848. };
  13849. return Database;
  13850. })();
  13851. BABYLON.Database = Database;
  13852. })(BABYLON || (BABYLON = {}));
  13853. //# sourceMappingURL=babylon.database.js.map
  13854. var BABYLON;
  13855. (function (BABYLON) {
  13856. var SpriteManager = (function () {
  13857. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  13858. this.name = name;
  13859. this.cellSize = cellSize;
  13860. this.sprites = new Array();
  13861. this.renderingGroupId = 0;
  13862. this.fogEnabled = true;
  13863. this._vertexDeclaration = [3, 4, 4, 4];
  13864. this._vertexStrideSize = 15 * 4;
  13865. this._capacity = capacity;
  13866. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  13867. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13868. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13869. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  13870. this._scene = scene;
  13871. this._scene.spriteManagers.push(this);
  13872. // VBO
  13873. this._vertexDeclaration = [3, 4, 4, 4];
  13874. this._vertexStrideSize = 15 * 4;
  13875. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13876. var indices = [];
  13877. var index = 0;
  13878. for (var count = 0; count < capacity; count++) {
  13879. indices.push(index);
  13880. indices.push(index + 1);
  13881. indices.push(index + 2);
  13882. indices.push(index);
  13883. indices.push(index + 2);
  13884. indices.push(index + 3);
  13885. index += 4;
  13886. }
  13887. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13888. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13889. // Effects
  13890. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  13891. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  13892. }
  13893. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  13894. var arrayOffset = index * 15;
  13895. if (offsetX == 0)
  13896. offsetX = this._epsilon;
  13897. else if (offsetX == 1)
  13898. offsetX = 1 - this._epsilon;
  13899. if (offsetY == 0)
  13900. offsetY = this._epsilon;
  13901. else if (offsetY == 1)
  13902. offsetY = 1 - this._epsilon;
  13903. this._vertices[arrayOffset] = sprite.position.x;
  13904. this._vertices[arrayOffset + 1] = sprite.position.y;
  13905. this._vertices[arrayOffset + 2] = sprite.position.z;
  13906. this._vertices[arrayOffset + 3] = sprite.angle;
  13907. this._vertices[arrayOffset + 4] = sprite.size;
  13908. this._vertices[arrayOffset + 5] = offsetX;
  13909. this._vertices[arrayOffset + 6] = offsetY;
  13910. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  13911. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  13912. var offset = (sprite.cellIndex / rowSize) >> 0;
  13913. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  13914. this._vertices[arrayOffset + 10] = offset;
  13915. // Color
  13916. this._vertices[arrayOffset + 11] = sprite.color.r;
  13917. this._vertices[arrayOffset + 12] = sprite.color.g;
  13918. this._vertices[arrayOffset + 13] = sprite.color.b;
  13919. this._vertices[arrayOffset + 14] = sprite.color.a;
  13920. };
  13921. SpriteManager.prototype.render = function () {
  13922. // Check
  13923. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  13924. return;
  13925. var engine = this._scene.getEngine();
  13926. var baseSize = this._spriteTexture.getBaseSize();
  13927. // Sprites
  13928. var deltaTime = engine.getDeltaTime();
  13929. var max = Math.min(this._capacity, this.sprites.length);
  13930. var rowSize = baseSize.width / this.cellSize;
  13931. var offset = 0;
  13932. for (var index = 0; index < max; index++) {
  13933. var sprite = this.sprites[index];
  13934. if (!sprite) {
  13935. continue;
  13936. }
  13937. sprite._animate(deltaTime);
  13938. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  13939. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  13940. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  13941. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  13942. }
  13943. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  13944. // Render
  13945. var effect = this._effectBase;
  13946. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13947. effect = this._effectFog;
  13948. }
  13949. engine.enableEffect(effect);
  13950. var viewMatrix = this._scene.getViewMatrix();
  13951. effect.setTexture("diffuseSampler", this._spriteTexture);
  13952. effect.setMatrix("view", viewMatrix);
  13953. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13954. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  13955. // Fog
  13956. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13957. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  13958. effect.setColor3("vFogColor", this._scene.fogColor);
  13959. }
  13960. // VBOs
  13961. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13962. // Draw order
  13963. effect.setBool("alphaTest", true);
  13964. engine.setColorWrite(false);
  13965. engine.draw(true, 0, max * 6);
  13966. engine.setColorWrite(true);
  13967. effect.setBool("alphaTest", false);
  13968. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13969. engine.draw(true, 0, max * 6);
  13970. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13971. };
  13972. SpriteManager.prototype.dispose = function () {
  13973. if (this._vertexBuffer) {
  13974. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13975. this._vertexBuffer = null;
  13976. }
  13977. if (this._indexBuffer) {
  13978. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13979. this._indexBuffer = null;
  13980. }
  13981. if (this._spriteTexture) {
  13982. this._spriteTexture.dispose();
  13983. this._spriteTexture = null;
  13984. }
  13985. // Remove from scene
  13986. var index = this._scene.spriteManagers.indexOf(this);
  13987. this._scene.spriteManagers.splice(index, 1);
  13988. // Callback
  13989. if (this.onDispose) {
  13990. this.onDispose();
  13991. }
  13992. };
  13993. return SpriteManager;
  13994. })();
  13995. BABYLON.SpriteManager = SpriteManager;
  13996. })(BABYLON || (BABYLON = {}));
  13997. //# sourceMappingURL=babylon.spriteManager.js.map
  13998. var BABYLON;
  13999. (function (BABYLON) {
  14000. var Sprite = (function () {
  14001. function Sprite(name, manager) {
  14002. this.name = name;
  14003. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14004. this.size = 1.0;
  14005. this.angle = 0;
  14006. this.cellIndex = 0;
  14007. this.invertU = 0;
  14008. this.invertV = 0;
  14009. this.animations = new Array();
  14010. this._animationStarted = false;
  14011. this._loopAnimation = false;
  14012. this._fromIndex = 0;
  14013. this._toIndex = 0;
  14014. this._delay = 0;
  14015. this._direction = 1;
  14016. this._frameCount = 0;
  14017. this._time = 0;
  14018. this._manager = manager;
  14019. this._manager.sprites.push(this);
  14020. this.position = BABYLON.Vector3.Zero();
  14021. }
  14022. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14023. this._fromIndex = from;
  14024. this._toIndex = to;
  14025. this._loopAnimation = loop;
  14026. this._delay = delay;
  14027. this._animationStarted = true;
  14028. this._direction = from < to ? 1 : -1;
  14029. this.cellIndex = from;
  14030. this._time = 0;
  14031. };
  14032. Sprite.prototype.stopAnimation = function () {
  14033. this._animationStarted = false;
  14034. };
  14035. Sprite.prototype._animate = function (deltaTime) {
  14036. if (!this._animationStarted)
  14037. return;
  14038. this._time += deltaTime;
  14039. if (this._time > this._delay) {
  14040. this._time = this._time % this._delay;
  14041. this.cellIndex += this._direction;
  14042. if (this.cellIndex == this._toIndex) {
  14043. if (this._loopAnimation) {
  14044. this.cellIndex = this._fromIndex;
  14045. } else {
  14046. this._animationStarted = false;
  14047. if (this.disposeWhenFinishedAnimating) {
  14048. this.dispose();
  14049. }
  14050. }
  14051. }
  14052. }
  14053. };
  14054. Sprite.prototype.dispose = function () {
  14055. for (var i = 0; i < this._manager.sprites.length; i++) {
  14056. if (this._manager.sprites[i] == this) {
  14057. this._manager.sprites.splice(i, 1);
  14058. }
  14059. }
  14060. };
  14061. return Sprite;
  14062. })();
  14063. BABYLON.Sprite = Sprite;
  14064. })(BABYLON || (BABYLON = {}));
  14065. //# sourceMappingURL=babylon.sprite.js.map
  14066. var BABYLON;
  14067. (function (BABYLON) {
  14068. var Layer = (function () {
  14069. function Layer(name, imgUrl, scene, isBackground, color) {
  14070. this.name = name;
  14071. this._vertexDeclaration = [2];
  14072. this._vertexStrideSize = 2 * 4;
  14073. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14074. this.isBackground = isBackground === undefined ? true : isBackground;
  14075. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14076. this._scene = scene;
  14077. this._scene.layers.push(this);
  14078. // VBO
  14079. var vertices = [];
  14080. vertices.push(1, 1);
  14081. vertices.push(-1, 1);
  14082. vertices.push(-1, -1);
  14083. vertices.push(1, -1);
  14084. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14085. // Indices
  14086. var indices = [];
  14087. indices.push(0);
  14088. indices.push(1);
  14089. indices.push(2);
  14090. indices.push(0);
  14091. indices.push(2);
  14092. indices.push(3);
  14093. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14094. // Effects
  14095. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14096. }
  14097. Layer.prototype.render = function () {
  14098. // Check
  14099. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14100. return;
  14101. var engine = this._scene.getEngine();
  14102. // Render
  14103. engine.enableEffect(this._effect);
  14104. engine.setState(false);
  14105. // Texture
  14106. this._effect.setTexture("textureSampler", this.texture);
  14107. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14108. // Color
  14109. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14110. // VBOs
  14111. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14112. // Draw order
  14113. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14114. engine.draw(true, 0, 6);
  14115. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14116. };
  14117. Layer.prototype.dispose = function () {
  14118. if (this._vertexBuffer) {
  14119. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14120. this._vertexBuffer = null;
  14121. }
  14122. if (this._indexBuffer) {
  14123. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14124. this._indexBuffer = null;
  14125. }
  14126. if (this.texture) {
  14127. this.texture.dispose();
  14128. this.texture = null;
  14129. }
  14130. // Remove from scene
  14131. var index = this._scene.layers.indexOf(this);
  14132. this._scene.layers.splice(index, 1);
  14133. // Callback
  14134. if (this.onDispose) {
  14135. this.onDispose();
  14136. }
  14137. };
  14138. return Layer;
  14139. })();
  14140. BABYLON.Layer = Layer;
  14141. })(BABYLON || (BABYLON = {}));
  14142. //# sourceMappingURL=babylon.layer.js.map
  14143. var BABYLON;
  14144. (function (BABYLON) {
  14145. var Particle = (function () {
  14146. function Particle() {
  14147. this.position = BABYLON.Vector3.Zero();
  14148. this.direction = BABYLON.Vector3.Zero();
  14149. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14150. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14151. this.lifeTime = 1.0;
  14152. this.age = 0;
  14153. this.size = 0;
  14154. this.angle = 0;
  14155. this.angularSpeed = 0;
  14156. }
  14157. Particle.prototype.copyTo = function (other) {
  14158. other.position.copyFrom(this.position);
  14159. other.direction.copyFrom(this.direction);
  14160. other.color.copyFrom(this.color);
  14161. other.colorStep.copyFrom(this.colorStep);
  14162. other.lifeTime = this.lifeTime;
  14163. other.age = this.age;
  14164. other.size = this.size;
  14165. other.angle = this.angle;
  14166. other.angularSpeed = this.angularSpeed;
  14167. };
  14168. return Particle;
  14169. })();
  14170. BABYLON.Particle = Particle;
  14171. })(BABYLON || (BABYLON = {}));
  14172. //# sourceMappingURL=babylon.particle.js.map
  14173. var BABYLON;
  14174. (function (BABYLON) {
  14175. var randomNumber = function (min, max) {
  14176. if (min === max) {
  14177. return (min);
  14178. }
  14179. var random = Math.random();
  14180. return ((random * (max - min)) + min);
  14181. };
  14182. var ParticleSystem = (function () {
  14183. function ParticleSystem(name, capacity, scene, customEffect) {
  14184. var _this = this;
  14185. this.name = name;
  14186. this.renderingGroupId = 0;
  14187. this.emitter = null;
  14188. this.emitRate = 10;
  14189. this.manualEmitCount = -1;
  14190. this.updateSpeed = 0.01;
  14191. this.targetStopDuration = 0;
  14192. this.disposeOnStop = false;
  14193. this.minEmitPower = 1;
  14194. this.maxEmitPower = 1;
  14195. this.minLifeTime = 1;
  14196. this.maxLifeTime = 1;
  14197. this.minSize = 1;
  14198. this.maxSize = 1;
  14199. this.minAngularSpeed = 0;
  14200. this.maxAngularSpeed = 0;
  14201. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14202. this.forceDepthWrite = false;
  14203. this.gravity = BABYLON.Vector3.Zero();
  14204. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14205. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14206. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14207. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14208. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14209. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14210. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14211. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14212. this.particles = new Array();
  14213. this._vertexDeclaration = [3, 4, 4];
  14214. this._vertexStrideSize = 11 * 4;
  14215. this._stockParticles = new Array();
  14216. this._newPartsExcess = 0;
  14217. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14218. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14219. this._scaledDirection = BABYLON.Vector3.Zero();
  14220. this._scaledGravity = BABYLON.Vector3.Zero();
  14221. this._currentRenderId = -1;
  14222. this._started = false;
  14223. this._stopped = false;
  14224. this._actualFrame = 0;
  14225. this.id = name;
  14226. this._capacity = capacity;
  14227. this._scene = scene;
  14228. this._customEffect = customEffect;
  14229. scene.particleSystems.push(this);
  14230. // VBO
  14231. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14232. var indices = [];
  14233. var index = 0;
  14234. for (var count = 0; count < capacity; count++) {
  14235. indices.push(index);
  14236. indices.push(index + 1);
  14237. indices.push(index + 2);
  14238. indices.push(index);
  14239. indices.push(index + 2);
  14240. indices.push(index + 3);
  14241. index += 4;
  14242. }
  14243. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14244. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14245. // Default behaviors
  14246. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14247. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14248. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14249. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14250. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14251. };
  14252. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14253. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14254. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14255. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14256. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14257. };
  14258. this.updateFunction = function (particles) {
  14259. for (var index = 0; index < particles.length; index++) {
  14260. var particle = particles[index];
  14261. particle.age += _this._scaledUpdateSpeed;
  14262. if (particle.age >= particle.lifeTime) {
  14263. _this.recycleParticle(particle);
  14264. index--;
  14265. continue;
  14266. } else {
  14267. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14268. particle.color.addInPlace(_this._scaledColorStep);
  14269. if (particle.color.a < 0)
  14270. particle.color.a = 0;
  14271. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14272. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14273. particle.position.addInPlace(_this._scaledDirection);
  14274. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14275. particle.direction.addInPlace(_this._scaledGravity);
  14276. }
  14277. }
  14278. };
  14279. }
  14280. ParticleSystem.prototype.recycleParticle = function (particle) {
  14281. var lastParticle = this.particles.pop();
  14282. if (lastParticle !== particle) {
  14283. lastParticle.copyTo(particle);
  14284. this._stockParticles.push(lastParticle);
  14285. }
  14286. };
  14287. ParticleSystem.prototype.getCapacity = function () {
  14288. return this._capacity;
  14289. };
  14290. ParticleSystem.prototype.isAlive = function () {
  14291. return this._alive;
  14292. };
  14293. ParticleSystem.prototype.isStarted = function () {
  14294. return this._started;
  14295. };
  14296. ParticleSystem.prototype.start = function () {
  14297. this._started = true;
  14298. this._stopped = false;
  14299. this._actualFrame = 0;
  14300. };
  14301. ParticleSystem.prototype.stop = function () {
  14302. this._stopped = true;
  14303. };
  14304. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14305. var offset = index * 11;
  14306. this._vertices[offset] = particle.position.x;
  14307. this._vertices[offset + 1] = particle.position.y;
  14308. this._vertices[offset + 2] = particle.position.z;
  14309. this._vertices[offset + 3] = particle.color.r;
  14310. this._vertices[offset + 4] = particle.color.g;
  14311. this._vertices[offset + 5] = particle.color.b;
  14312. this._vertices[offset + 6] = particle.color.a;
  14313. this._vertices[offset + 7] = particle.angle;
  14314. this._vertices[offset + 8] = particle.size;
  14315. this._vertices[offset + 9] = offsetX;
  14316. this._vertices[offset + 10] = offsetY;
  14317. };
  14318. ParticleSystem.prototype._update = function (newParticles) {
  14319. // Update current
  14320. this._alive = this.particles.length > 0;
  14321. this.updateFunction(this.particles);
  14322. // Add new ones
  14323. var worldMatrix;
  14324. if (this.emitter.position) {
  14325. worldMatrix = this.emitter.getWorldMatrix();
  14326. } else {
  14327. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14328. }
  14329. for (var index = 0; index < newParticles; index++) {
  14330. if (this.particles.length === this._capacity) {
  14331. break;
  14332. }
  14333. if (this._stockParticles.length !== 0) {
  14334. var particle = this._stockParticles.pop();
  14335. particle.age = 0;
  14336. } else {
  14337. particle = new BABYLON.Particle();
  14338. }
  14339. this.particles.push(particle);
  14340. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14341. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14342. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14343. particle.size = randomNumber(this.minSize, this.maxSize);
  14344. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14345. this.startPositionFunction(worldMatrix, particle.position);
  14346. var step = randomNumber(0, 1.0);
  14347. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14348. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14349. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14350. }
  14351. };
  14352. ParticleSystem.prototype._getEffect = function () {
  14353. if (this._customEffect) {
  14354. return this._customEffect;
  14355. }
  14356. ;
  14357. var defines = [];
  14358. if (this._scene.clipPlane) {
  14359. defines.push("#define CLIPPLANE");
  14360. }
  14361. // Effect
  14362. var join = defines.join("\n");
  14363. if (this._cachedDefines !== join) {
  14364. this._cachedDefines = join;
  14365. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14366. }
  14367. return this._effect;
  14368. };
  14369. ParticleSystem.prototype.animate = function () {
  14370. if (!this._started)
  14371. return;
  14372. var effect = this._getEffect();
  14373. // Check
  14374. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14375. return;
  14376. if (this._currentRenderId === this._scene.getRenderId()) {
  14377. return;
  14378. }
  14379. this._currentRenderId = this._scene.getRenderId();
  14380. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14381. // determine the number of particles we need to create
  14382. var emitCout;
  14383. if (this.manualEmitCount > -1) {
  14384. emitCout = this.manualEmitCount;
  14385. this.manualEmitCount = 0;
  14386. } else {
  14387. emitCout = this.emitRate;
  14388. }
  14389. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14390. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14391. if (this._newPartsExcess > 1.0) {
  14392. newParticles += this._newPartsExcess >> 0;
  14393. this._newPartsExcess -= this._newPartsExcess >> 0;
  14394. }
  14395. this._alive = false;
  14396. if (!this._stopped) {
  14397. this._actualFrame += this._scaledUpdateSpeed;
  14398. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14399. this.stop();
  14400. } else {
  14401. newParticles = 0;
  14402. }
  14403. this._update(newParticles);
  14404. // Stopped?
  14405. if (this._stopped) {
  14406. if (!this._alive) {
  14407. this._started = false;
  14408. if (this.disposeOnStop) {
  14409. this._scene._toBeDisposed.push(this);
  14410. }
  14411. }
  14412. }
  14413. // Update VBO
  14414. var offset = 0;
  14415. for (var index = 0; index < this.particles.length; index++) {
  14416. var particle = this.particles[index];
  14417. this._appendParticleVertex(offset++, particle, 0, 0);
  14418. this._appendParticleVertex(offset++, particle, 1, 0);
  14419. this._appendParticleVertex(offset++, particle, 1, 1);
  14420. this._appendParticleVertex(offset++, particle, 0, 1);
  14421. }
  14422. var engine = this._scene.getEngine();
  14423. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14424. };
  14425. ParticleSystem.prototype.render = function () {
  14426. var effect = this._getEffect();
  14427. // Check
  14428. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14429. return 0;
  14430. var engine = this._scene.getEngine();
  14431. // Render
  14432. engine.enableEffect(effect);
  14433. engine.setState(false);
  14434. var viewMatrix = this._scene.getViewMatrix();
  14435. effect.setTexture("diffuseSampler", this.particleTexture);
  14436. effect.setMatrix("view", viewMatrix);
  14437. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14438. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14439. if (this._scene.clipPlane) {
  14440. var clipPlane = this._scene.clipPlane;
  14441. var invView = viewMatrix.clone();
  14442. invView.invert();
  14443. effect.setMatrix("invView", invView);
  14444. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14445. }
  14446. // VBOs
  14447. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14448. // Draw order
  14449. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14450. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14451. } else {
  14452. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14453. }
  14454. if (this.forceDepthWrite) {
  14455. engine.setDepthWrite(true);
  14456. }
  14457. engine.draw(true, 0, this.particles.length * 6);
  14458. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14459. return this.particles.length;
  14460. };
  14461. ParticleSystem.prototype.dispose = function () {
  14462. if (this._vertexBuffer) {
  14463. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14464. this._vertexBuffer = null;
  14465. }
  14466. if (this._indexBuffer) {
  14467. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14468. this._indexBuffer = null;
  14469. }
  14470. if (this.particleTexture) {
  14471. this.particleTexture.dispose();
  14472. this.particleTexture = null;
  14473. }
  14474. // Remove from scene
  14475. var index = this._scene.particleSystems.indexOf(this);
  14476. this._scene.particleSystems.splice(index, 1);
  14477. // Callback
  14478. if (this.onDispose) {
  14479. this.onDispose();
  14480. }
  14481. };
  14482. // Clone
  14483. ParticleSystem.prototype.clone = function (name, newEmitter) {
  14484. var result = new ParticleSystem(name, this._capacity, this._scene);
  14485. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  14486. if (newEmitter === undefined) {
  14487. newEmitter = this.emitter;
  14488. }
  14489. result.emitter = newEmitter;
  14490. if (this.particleTexture) {
  14491. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  14492. }
  14493. result.start();
  14494. return result;
  14495. };
  14496. ParticleSystem.BLENDMODE_ONEONE = 0;
  14497. ParticleSystem.BLENDMODE_STANDARD = 1;
  14498. return ParticleSystem;
  14499. })();
  14500. BABYLON.ParticleSystem = ParticleSystem;
  14501. })(BABYLON || (BABYLON = {}));
  14502. //# sourceMappingURL=babylon.particleSystem.js.map
  14503. var BABYLON;
  14504. (function (BABYLON) {
  14505. var Animation = (function () {
  14506. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  14507. this.name = name;
  14508. this.targetProperty = targetProperty;
  14509. this.framePerSecond = framePerSecond;
  14510. this.dataType = dataType;
  14511. this.loopMode = loopMode;
  14512. this._offsetsCache = {};
  14513. this._highLimitsCache = {};
  14514. this._stopped = false;
  14515. this.targetPropertyPath = targetProperty.split(".");
  14516. this.dataType = dataType;
  14517. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  14518. }
  14519. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  14520. var dataType = undefined;
  14521. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  14522. dataType = Animation.ANIMATIONTYPE_FLOAT;
  14523. } else if (from instanceof BABYLON.Quaternion) {
  14524. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  14525. } else if (from instanceof BABYLON.Vector3) {
  14526. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  14527. } else if (from instanceof BABYLON.Vector2) {
  14528. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  14529. } else if (from instanceof BABYLON.Color3) {
  14530. dataType = Animation.ANIMATIONTYPE_COLOR3;
  14531. }
  14532. if (dataType == undefined) {
  14533. return;
  14534. }
  14535. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  14536. var keys = [];
  14537. keys.push({ frame: 0, value: from });
  14538. keys.push({ frame: totalFrame, value: to });
  14539. animation.setKeys(keys);
  14540. mesh.animations.push(animation);
  14541. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  14542. };
  14543. // Methods
  14544. Animation.prototype.isStopped = function () {
  14545. return this._stopped;
  14546. };
  14547. Animation.prototype.getKeys = function () {
  14548. return this._keys;
  14549. };
  14550. Animation.prototype.getEasingFunction = function () {
  14551. return this._easingFunction;
  14552. };
  14553. Animation.prototype.setEasingFunction = function (easingFunction) {
  14554. this._easingFunction = easingFunction;
  14555. };
  14556. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  14557. return startValue + (endValue - startValue) * gradient;
  14558. };
  14559. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  14560. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  14561. };
  14562. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  14563. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  14564. };
  14565. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  14566. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  14567. };
  14568. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  14569. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  14570. };
  14571. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  14572. var startScale = new BABYLON.Vector3(0, 0, 0);
  14573. var startRotation = new BABYLON.Quaternion();
  14574. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  14575. startValue.decompose(startScale, startRotation, startTranslation);
  14576. var endScale = new BABYLON.Vector3(0, 0, 0);
  14577. var endRotation = new BABYLON.Quaternion();
  14578. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  14579. endValue.decompose(endScale, endRotation, endTranslation);
  14580. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  14581. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  14582. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  14583. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  14584. return result;
  14585. };
  14586. Animation.prototype.clone = function () {
  14587. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  14588. clone.setKeys(this._keys);
  14589. return clone;
  14590. };
  14591. Animation.prototype.setKeys = function (values) {
  14592. this._keys = values.slice(0);
  14593. this._offsetsCache = {};
  14594. this._highLimitsCache = {};
  14595. };
  14596. Animation.prototype._getKeyValue = function (value) {
  14597. if (typeof value === "function") {
  14598. return value();
  14599. }
  14600. return value;
  14601. };
  14602. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  14603. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  14604. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  14605. }
  14606. this.currentFrame = currentFrame;
  14607. for (var key = 0; key < this._keys.length; key++) {
  14608. // for each frame, we need the key just before the frame superior
  14609. if (this._keys[key + 1].frame >= currentFrame) {
  14610. var startValue = this._getKeyValue(this._keys[key].value);
  14611. var endValue = this._getKeyValue(this._keys[key + 1].value);
  14612. // gradient : percent of currentFrame between the frame inf and the frame sup
  14613. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  14614. // check for easingFunction and correction of gradient
  14615. if (this._easingFunction != null) {
  14616. gradient = this._easingFunction.ease(gradient);
  14617. }
  14618. switch (this.dataType) {
  14619. case Animation.ANIMATIONTYPE_FLOAT:
  14620. switch (loopMode) {
  14621. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14622. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14623. return this.floatInterpolateFunction(startValue, endValue, gradient);
  14624. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14625. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  14626. }
  14627. break;
  14628. case Animation.ANIMATIONTYPE_QUATERNION:
  14629. var quaternion = null;
  14630. switch (loopMode) {
  14631. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14632. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14633. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  14634. break;
  14635. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14636. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14637. break;
  14638. }
  14639. return quaternion;
  14640. case Animation.ANIMATIONTYPE_VECTOR3:
  14641. switch (loopMode) {
  14642. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14643. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14644. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  14645. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14646. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14647. }
  14648. case Animation.ANIMATIONTYPE_VECTOR2:
  14649. switch (loopMode) {
  14650. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14651. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14652. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  14653. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14654. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14655. }
  14656. case Animation.ANIMATIONTYPE_COLOR3:
  14657. switch (loopMode) {
  14658. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14659. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14660. return this.color3InterpolateFunction(startValue, endValue, gradient);
  14661. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14662. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14663. }
  14664. case Animation.ANIMATIONTYPE_MATRIX:
  14665. switch (loopMode) {
  14666. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14667. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14668. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  14669. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14670. return startValue;
  14671. }
  14672. default:
  14673. break;
  14674. }
  14675. break;
  14676. }
  14677. }
  14678. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  14679. };
  14680. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  14681. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  14682. this._stopped = true;
  14683. return false;
  14684. }
  14685. var returnValue = true;
  14686. // Adding a start key at frame 0 if missing
  14687. if (this._keys[0].frame !== 0) {
  14688. var newKey = { frame: 0, value: this._keys[0].value };
  14689. this._keys.splice(0, 0, newKey);
  14690. }
  14691. // Check limits
  14692. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  14693. from = this._keys[0].frame;
  14694. }
  14695. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  14696. to = this._keys[this._keys.length - 1].frame;
  14697. }
  14698. // Compute ratio
  14699. var range = to - from;
  14700. var offsetValue;
  14701. // ratio represents the frame delta between from and to
  14702. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  14703. var highLimitValue = 0;
  14704. if (ratio > range && !loop) {
  14705. returnValue = false;
  14706. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  14707. } else {
  14708. // Get max value if required
  14709. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  14710. var keyOffset = to.toString() + from.toString();
  14711. if (!this._offsetsCache[keyOffset]) {
  14712. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14713. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14714. switch (this.dataType) {
  14715. case Animation.ANIMATIONTYPE_FLOAT:
  14716. this._offsetsCache[keyOffset] = toValue - fromValue;
  14717. break;
  14718. case Animation.ANIMATIONTYPE_QUATERNION:
  14719. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14720. break;
  14721. case Animation.ANIMATIONTYPE_VECTOR3:
  14722. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14723. case Animation.ANIMATIONTYPE_VECTOR2:
  14724. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14725. case Animation.ANIMATIONTYPE_COLOR3:
  14726. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14727. default:
  14728. break;
  14729. }
  14730. this._highLimitsCache[keyOffset] = toValue;
  14731. }
  14732. highLimitValue = this._highLimitsCache[keyOffset];
  14733. offsetValue = this._offsetsCache[keyOffset];
  14734. }
  14735. }
  14736. if (offsetValue === undefined) {
  14737. switch (this.dataType) {
  14738. case Animation.ANIMATIONTYPE_FLOAT:
  14739. offsetValue = 0;
  14740. break;
  14741. case Animation.ANIMATIONTYPE_QUATERNION:
  14742. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  14743. break;
  14744. case Animation.ANIMATIONTYPE_VECTOR3:
  14745. offsetValue = BABYLON.Vector3.Zero();
  14746. break;
  14747. case Animation.ANIMATIONTYPE_VECTOR2:
  14748. offsetValue = BABYLON.Vector2.Zero();
  14749. break;
  14750. case Animation.ANIMATIONTYPE_COLOR3:
  14751. offsetValue = BABYLON.Color3.Black();
  14752. }
  14753. }
  14754. // Compute value
  14755. var repeatCount = (ratio / range) >> 0;
  14756. var currentFrame = returnValue ? from + ratio % range : to;
  14757. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  14758. // Set value
  14759. if (this.targetPropertyPath.length > 1) {
  14760. var property = this._target[this.targetPropertyPath[0]];
  14761. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  14762. property = property[this.targetPropertyPath[index]];
  14763. }
  14764. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  14765. } else {
  14766. this._target[this.targetPropertyPath[0]] = currentValue;
  14767. }
  14768. if (this._target.markAsDirty) {
  14769. this._target.markAsDirty(this.targetProperty);
  14770. }
  14771. if (!returnValue) {
  14772. this._stopped = true;
  14773. }
  14774. return returnValue;
  14775. };
  14776. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  14777. get: function () {
  14778. return Animation._ANIMATIONTYPE_FLOAT;
  14779. },
  14780. enumerable: true,
  14781. configurable: true
  14782. });
  14783. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  14784. get: function () {
  14785. return Animation._ANIMATIONTYPE_VECTOR3;
  14786. },
  14787. enumerable: true,
  14788. configurable: true
  14789. });
  14790. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  14791. get: function () {
  14792. return Animation._ANIMATIONTYPE_VECTOR2;
  14793. },
  14794. enumerable: true,
  14795. configurable: true
  14796. });
  14797. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  14798. get: function () {
  14799. return Animation._ANIMATIONTYPE_QUATERNION;
  14800. },
  14801. enumerable: true,
  14802. configurable: true
  14803. });
  14804. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  14805. get: function () {
  14806. return Animation._ANIMATIONTYPE_MATRIX;
  14807. },
  14808. enumerable: true,
  14809. configurable: true
  14810. });
  14811. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  14812. get: function () {
  14813. return Animation._ANIMATIONTYPE_COLOR3;
  14814. },
  14815. enumerable: true,
  14816. configurable: true
  14817. });
  14818. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  14819. get: function () {
  14820. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  14821. },
  14822. enumerable: true,
  14823. configurable: true
  14824. });
  14825. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  14826. get: function () {
  14827. return Animation._ANIMATIONLOOPMODE_CYCLE;
  14828. },
  14829. enumerable: true,
  14830. configurable: true
  14831. });
  14832. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  14833. get: function () {
  14834. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  14835. },
  14836. enumerable: true,
  14837. configurable: true
  14838. });
  14839. Animation._ANIMATIONTYPE_FLOAT = 0;
  14840. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  14841. Animation._ANIMATIONTYPE_QUATERNION = 2;
  14842. Animation._ANIMATIONTYPE_MATRIX = 3;
  14843. Animation._ANIMATIONTYPE_COLOR3 = 4;
  14844. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  14845. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  14846. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  14847. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  14848. return Animation;
  14849. })();
  14850. BABYLON.Animation = Animation;
  14851. })(BABYLON || (BABYLON = {}));
  14852. //# sourceMappingURL=babylon.animation.js.map
  14853. var BABYLON;
  14854. (function (BABYLON) {
  14855. var Animatable = (function () {
  14856. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  14857. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  14858. if (typeof toFrame === "undefined") { toFrame = 100; }
  14859. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  14860. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  14861. this.target = target;
  14862. this.fromFrame = fromFrame;
  14863. this.toFrame = toFrame;
  14864. this.loopAnimation = loopAnimation;
  14865. this.speedRatio = speedRatio;
  14866. this.onAnimationEnd = onAnimationEnd;
  14867. this._animations = new Array();
  14868. this._paused = false;
  14869. this.animationStarted = false;
  14870. if (animations) {
  14871. this.appendAnimations(target, animations);
  14872. }
  14873. this._scene = scene;
  14874. scene._activeAnimatables.push(this);
  14875. }
  14876. // Methods
  14877. Animatable.prototype.appendAnimations = function (target, animations) {
  14878. for (var index = 0; index < animations.length; index++) {
  14879. var animation = animations[index];
  14880. animation._target = target;
  14881. this._animations.push(animation);
  14882. }
  14883. };
  14884. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  14885. var animations = this._animations;
  14886. for (var index = 0; index < animations.length; index++) {
  14887. if (animations[index].targetProperty === property) {
  14888. return animations[index];
  14889. }
  14890. }
  14891. return null;
  14892. };
  14893. Animatable.prototype.pause = function () {
  14894. if (this._paused) {
  14895. return;
  14896. }
  14897. this._paused = true;
  14898. };
  14899. Animatable.prototype.restart = function () {
  14900. this._paused = false;
  14901. };
  14902. Animatable.prototype.stop = function () {
  14903. var index = this._scene._activeAnimatables.indexOf(this);
  14904. if (index > -1) {
  14905. this._scene._activeAnimatables.splice(index, 1);
  14906. }
  14907. if (this.onAnimationEnd) {
  14908. this.onAnimationEnd();
  14909. }
  14910. };
  14911. Animatable.prototype._animate = function (delay) {
  14912. if (this._paused) {
  14913. if (!this._pausedDelay) {
  14914. this._pausedDelay = delay;
  14915. }
  14916. return true;
  14917. }
  14918. if (!this._localDelayOffset) {
  14919. this._localDelayOffset = delay;
  14920. } else if (this._pausedDelay) {
  14921. this._localDelayOffset += delay - this._pausedDelay;
  14922. this._pausedDelay = null;
  14923. }
  14924. // Animating
  14925. var running = false;
  14926. var animations = this._animations;
  14927. for (var index = 0; index < animations.length; index++) {
  14928. var animation = animations[index];
  14929. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  14930. running = running || isRunning;
  14931. }
  14932. if (!running && this.onAnimationEnd) {
  14933. this.onAnimationEnd();
  14934. }
  14935. return running;
  14936. };
  14937. return Animatable;
  14938. })();
  14939. BABYLON.Animatable = Animatable;
  14940. })(BABYLON || (BABYLON = {}));
  14941. //# sourceMappingURL=babylon.animatable.js.map
  14942. var BABYLON;
  14943. (function (BABYLON) {
  14944. var EasingFunction = (function () {
  14945. function EasingFunction() {
  14946. // Properties
  14947. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  14948. }
  14949. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  14950. get: function () {
  14951. return EasingFunction._EASINGMODE_EASEIN;
  14952. },
  14953. enumerable: true,
  14954. configurable: true
  14955. });
  14956. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  14957. get: function () {
  14958. return EasingFunction._EASINGMODE_EASEOUT;
  14959. },
  14960. enumerable: true,
  14961. configurable: true
  14962. });
  14963. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  14964. get: function () {
  14965. return EasingFunction._EASINGMODE_EASEINOUT;
  14966. },
  14967. enumerable: true,
  14968. configurable: true
  14969. });
  14970. EasingFunction.prototype.setEasingMode = function (easingMode) {
  14971. var n = Math.min(Math.max(easingMode, 0), 2);
  14972. this._easingMode = n;
  14973. };
  14974. EasingFunction.prototype.getEasingMode = function () {
  14975. return this._easingMode;
  14976. };
  14977. EasingFunction.prototype.easeInCore = function (gradient) {
  14978. throw new Error('You must implement this method');
  14979. };
  14980. EasingFunction.prototype.ease = function (gradient) {
  14981. switch (this._easingMode) {
  14982. case EasingFunction.EASINGMODE_EASEIN:
  14983. return this.easeInCore(gradient);
  14984. case EasingFunction.EASINGMODE_EASEOUT:
  14985. return (1 - this.easeInCore(1 - gradient));
  14986. }
  14987. if (gradient >= 0.5) {
  14988. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  14989. }
  14990. return (this.easeInCore(gradient * 2) * 0.5);
  14991. };
  14992. EasingFunction._EASINGMODE_EASEIN = 0;
  14993. EasingFunction._EASINGMODE_EASEOUT = 1;
  14994. EasingFunction._EASINGMODE_EASEINOUT = 2;
  14995. return EasingFunction;
  14996. })();
  14997. BABYLON.EasingFunction = EasingFunction;
  14998. var CircleEase = (function (_super) {
  14999. __extends(CircleEase, _super);
  15000. function CircleEase() {
  15001. _super.apply(this, arguments);
  15002. }
  15003. CircleEase.prototype.easeInCore = function (gradient) {
  15004. gradient = Math.max(0, Math.min(1, gradient));
  15005. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15006. };
  15007. return CircleEase;
  15008. })(EasingFunction);
  15009. BABYLON.CircleEase = CircleEase;
  15010. var BackEase = (function (_super) {
  15011. __extends(BackEase, _super);
  15012. function BackEase(amplitude) {
  15013. if (typeof amplitude === "undefined") { amplitude = 1; }
  15014. _super.call(this);
  15015. this.amplitude = amplitude;
  15016. }
  15017. BackEase.prototype.easeInCore = function (gradient) {
  15018. var num = Math.max(0, this.amplitude);
  15019. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15020. };
  15021. return BackEase;
  15022. })(EasingFunction);
  15023. BABYLON.BackEase = BackEase;
  15024. var BounceEase = (function (_super) {
  15025. __extends(BounceEase, _super);
  15026. function BounceEase(bounces, bounciness) {
  15027. if (typeof bounces === "undefined") { bounces = 3; }
  15028. if (typeof bounciness === "undefined") { bounciness = 2; }
  15029. _super.call(this);
  15030. this.bounces = bounces;
  15031. this.bounciness = bounciness;
  15032. }
  15033. BounceEase.prototype.easeInCore = function (gradient) {
  15034. var y = Math.max(0.0, this.bounces);
  15035. var bounciness = this.bounciness;
  15036. if (bounciness <= 1.0) {
  15037. bounciness = 1.001;
  15038. }
  15039. var num9 = Math.pow(bounciness, y);
  15040. var num5 = 1.0 - bounciness;
  15041. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15042. var num15 = gradient * num4;
  15043. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15044. var num3 = Math.floor(num65);
  15045. var num13 = num3 + 1.0;
  15046. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15047. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15048. var num7 = (num8 + num12) * 0.5;
  15049. var num6 = gradient - num7;
  15050. var num2 = num7 - num8;
  15051. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15052. };
  15053. return BounceEase;
  15054. })(EasingFunction);
  15055. BABYLON.BounceEase = BounceEase;
  15056. var CubicEase = (function (_super) {
  15057. __extends(CubicEase, _super);
  15058. function CubicEase() {
  15059. _super.apply(this, arguments);
  15060. }
  15061. CubicEase.prototype.easeInCore = function (gradient) {
  15062. return (gradient * gradient * gradient);
  15063. };
  15064. return CubicEase;
  15065. })(EasingFunction);
  15066. BABYLON.CubicEase = CubicEase;
  15067. var ElasticEase = (function (_super) {
  15068. __extends(ElasticEase, _super);
  15069. function ElasticEase(oscillations, springiness) {
  15070. if (typeof oscillations === "undefined") { oscillations = 3; }
  15071. if (typeof springiness === "undefined") { springiness = 3; }
  15072. _super.call(this);
  15073. this.oscillations = oscillations;
  15074. this.springiness = springiness;
  15075. }
  15076. ElasticEase.prototype.easeInCore = function (gradient) {
  15077. var num2;
  15078. var num3 = Math.max(0.0, this.oscillations);
  15079. var num = Math.max(0.0, this.springiness);
  15080. if (num == 0) {
  15081. num2 = gradient;
  15082. } else {
  15083. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15084. }
  15085. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15086. };
  15087. return ElasticEase;
  15088. })(EasingFunction);
  15089. BABYLON.ElasticEase = ElasticEase;
  15090. var ExponentialEase = (function (_super) {
  15091. __extends(ExponentialEase, _super);
  15092. function ExponentialEase(exponent) {
  15093. if (typeof exponent === "undefined") { exponent = 2; }
  15094. _super.call(this);
  15095. this.exponent = exponent;
  15096. }
  15097. ExponentialEase.prototype.easeInCore = function (gradient) {
  15098. if (this.exponent <= 0) {
  15099. return gradient;
  15100. }
  15101. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15102. };
  15103. return ExponentialEase;
  15104. })(EasingFunction);
  15105. BABYLON.ExponentialEase = ExponentialEase;
  15106. var PowerEase = (function (_super) {
  15107. __extends(PowerEase, _super);
  15108. function PowerEase(power) {
  15109. if (typeof power === "undefined") { power = 2; }
  15110. _super.call(this);
  15111. this.power = power;
  15112. }
  15113. PowerEase.prototype.easeInCore = function (gradient) {
  15114. var y = Math.max(0.0, this.power);
  15115. return Math.pow(gradient, y);
  15116. };
  15117. return PowerEase;
  15118. })(EasingFunction);
  15119. BABYLON.PowerEase = PowerEase;
  15120. var QuadraticEase = (function (_super) {
  15121. __extends(QuadraticEase, _super);
  15122. function QuadraticEase() {
  15123. _super.apply(this, arguments);
  15124. }
  15125. QuadraticEase.prototype.easeInCore = function (gradient) {
  15126. return (gradient * gradient);
  15127. };
  15128. return QuadraticEase;
  15129. })(EasingFunction);
  15130. BABYLON.QuadraticEase = QuadraticEase;
  15131. var QuarticEase = (function (_super) {
  15132. __extends(QuarticEase, _super);
  15133. function QuarticEase() {
  15134. _super.apply(this, arguments);
  15135. }
  15136. QuarticEase.prototype.easeInCore = function (gradient) {
  15137. return (gradient * gradient * gradient * gradient);
  15138. };
  15139. return QuarticEase;
  15140. })(EasingFunction);
  15141. BABYLON.QuarticEase = QuarticEase;
  15142. var QuinticEase = (function (_super) {
  15143. __extends(QuinticEase, _super);
  15144. function QuinticEase() {
  15145. _super.apply(this, arguments);
  15146. }
  15147. QuinticEase.prototype.easeInCore = function (gradient) {
  15148. return (gradient * gradient * gradient * gradient * gradient);
  15149. };
  15150. return QuinticEase;
  15151. })(EasingFunction);
  15152. BABYLON.QuinticEase = QuinticEase;
  15153. var SineEase = (function (_super) {
  15154. __extends(SineEase, _super);
  15155. function SineEase() {
  15156. _super.apply(this, arguments);
  15157. }
  15158. SineEase.prototype.easeInCore = function (gradient) {
  15159. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15160. };
  15161. return SineEase;
  15162. })(EasingFunction);
  15163. BABYLON.SineEase = SineEase;
  15164. var BezierCurveEase = (function (_super) {
  15165. __extends(BezierCurveEase, _super);
  15166. function BezierCurveEase(x1, y1, x2, y2) {
  15167. if (typeof x1 === "undefined") { x1 = 0; }
  15168. if (typeof y1 === "undefined") { y1 = 0; }
  15169. if (typeof x2 === "undefined") { x2 = 1; }
  15170. if (typeof y2 === "undefined") { y2 = 1; }
  15171. _super.call(this);
  15172. this.x1 = x1;
  15173. this.y1 = y1;
  15174. this.x2 = x2;
  15175. this.y2 = y2;
  15176. }
  15177. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15178. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15179. };
  15180. return BezierCurveEase;
  15181. })(EasingFunction);
  15182. BABYLON.BezierCurveEase = BezierCurveEase;
  15183. })(BABYLON || (BABYLON = {}));
  15184. //# sourceMappingURL=babylon.easing.js.map
  15185. var BABYLON;
  15186. (function (BABYLON) {
  15187. var Octree = (function () {
  15188. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15189. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  15190. this.maxDepth = maxDepth;
  15191. this.dynamicContent = new Array();
  15192. this._maxBlockCapacity = maxBlockCapacity || 64;
  15193. this._selectionContent = new BABYLON.SmartArray(1024);
  15194. this._creationFunc = creationFunc;
  15195. }
  15196. // Methods
  15197. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15198. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15199. };
  15200. Octree.prototype.addMesh = function (entry) {
  15201. for (var index = 0; index < this.blocks.length; index++) {
  15202. var block = this.blocks[index];
  15203. block.addEntry(entry);
  15204. }
  15205. };
  15206. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15207. this._selectionContent.reset();
  15208. for (var index = 0; index < this.blocks.length; index++) {
  15209. var block = this.blocks[index];
  15210. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15211. }
  15212. if (allowDuplicate) {
  15213. this._selectionContent.concat(this.dynamicContent);
  15214. } else {
  15215. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15216. }
  15217. return this._selectionContent;
  15218. };
  15219. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15220. this._selectionContent.reset();
  15221. for (var index = 0; index < this.blocks.length; index++) {
  15222. var block = this.blocks[index];
  15223. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15224. }
  15225. if (allowDuplicate) {
  15226. this._selectionContent.concat(this.dynamicContent);
  15227. } else {
  15228. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15229. }
  15230. return this._selectionContent;
  15231. };
  15232. Octree.prototype.intersectsRay = function (ray) {
  15233. this._selectionContent.reset();
  15234. for (var index = 0; index < this.blocks.length; index++) {
  15235. var block = this.blocks[index];
  15236. block.intersectsRay(ray, this._selectionContent);
  15237. }
  15238. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15239. return this._selectionContent;
  15240. };
  15241. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  15242. target.blocks = new Array();
  15243. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  15244. for (var x = 0; x < 2; x++) {
  15245. for (var y = 0; y < 2; y++) {
  15246. for (var z = 0; z < 2; z++) {
  15247. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  15248. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  15249. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  15250. block.addEntries(entries);
  15251. target.blocks.push(block);
  15252. }
  15253. }
  15254. }
  15255. };
  15256. Octree.CreationFuncForMeshes = function (entry, block) {
  15257. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15258. block.entries.push(entry);
  15259. }
  15260. };
  15261. Octree.CreationFuncForSubMeshes = function (entry, block) {
  15262. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15263. block.entries.push(entry);
  15264. }
  15265. };
  15266. return Octree;
  15267. })();
  15268. BABYLON.Octree = Octree;
  15269. })(BABYLON || (BABYLON = {}));
  15270. //# sourceMappingURL=babylon.octree.js.map
  15271. var BABYLON;
  15272. (function (BABYLON) {
  15273. var OctreeBlock = (function () {
  15274. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15275. this.entries = new Array();
  15276. this._boundingVectors = new Array();
  15277. this._capacity = capacity;
  15278. this._depth = depth;
  15279. this._maxDepth = maxDepth;
  15280. this._creationFunc = creationFunc;
  15281. this._minPoint = minPoint;
  15282. this._maxPoint = maxPoint;
  15283. this._boundingVectors.push(minPoint.clone());
  15284. this._boundingVectors.push(maxPoint.clone());
  15285. this._boundingVectors.push(minPoint.clone());
  15286. this._boundingVectors[2].x = maxPoint.x;
  15287. this._boundingVectors.push(minPoint.clone());
  15288. this._boundingVectors[3].y = maxPoint.y;
  15289. this._boundingVectors.push(minPoint.clone());
  15290. this._boundingVectors[4].z = maxPoint.z;
  15291. this._boundingVectors.push(maxPoint.clone());
  15292. this._boundingVectors[5].z = minPoint.z;
  15293. this._boundingVectors.push(maxPoint.clone());
  15294. this._boundingVectors[6].x = minPoint.x;
  15295. this._boundingVectors.push(maxPoint.clone());
  15296. this._boundingVectors[7].y = minPoint.y;
  15297. }
  15298. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15299. // Property
  15300. get: function () {
  15301. return this._capacity;
  15302. },
  15303. enumerable: true,
  15304. configurable: true
  15305. });
  15306. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15307. get: function () {
  15308. return this._minPoint;
  15309. },
  15310. enumerable: true,
  15311. configurable: true
  15312. });
  15313. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15314. get: function () {
  15315. return this._maxPoint;
  15316. },
  15317. enumerable: true,
  15318. configurable: true
  15319. });
  15320. // Methods
  15321. OctreeBlock.prototype.addEntry = function (entry) {
  15322. if (this.blocks) {
  15323. for (var index = 0; index < this.blocks.length; index++) {
  15324. var block = this.blocks[index];
  15325. block.addEntry(entry);
  15326. }
  15327. return;
  15328. }
  15329. this._creationFunc(entry, this);
  15330. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15331. this.createInnerBlocks();
  15332. }
  15333. };
  15334. OctreeBlock.prototype.addEntries = function (entries) {
  15335. for (var index = 0; index < entries.length; index++) {
  15336. var mesh = entries[index];
  15337. this.addEntry(mesh);
  15338. }
  15339. };
  15340. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15341. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15342. if (this.blocks) {
  15343. for (var index = 0; index < this.blocks.length; index++) {
  15344. var block = this.blocks[index];
  15345. block.select(frustumPlanes, selection, allowDuplicate);
  15346. }
  15347. return;
  15348. }
  15349. if (allowDuplicate) {
  15350. selection.concat(this.entries);
  15351. } else {
  15352. selection.concatWithNoDuplicate(this.entries);
  15353. }
  15354. }
  15355. };
  15356. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15357. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15358. if (this.blocks) {
  15359. for (var index = 0; index < this.blocks.length; index++) {
  15360. var block = this.blocks[index];
  15361. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15362. }
  15363. return;
  15364. }
  15365. if (allowDuplicate) {
  15366. selection.concat(this.entries);
  15367. } else {
  15368. selection.concatWithNoDuplicate(this.entries);
  15369. }
  15370. }
  15371. };
  15372. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15373. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15374. if (this.blocks) {
  15375. for (var index = 0; index < this.blocks.length; index++) {
  15376. var block = this.blocks[index];
  15377. block.intersectsRay(ray, selection);
  15378. }
  15379. return;
  15380. }
  15381. selection.concatWithNoDuplicate(this.entries);
  15382. }
  15383. };
  15384. OctreeBlock.prototype.createInnerBlocks = function () {
  15385. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15386. };
  15387. return OctreeBlock;
  15388. })();
  15389. BABYLON.OctreeBlock = OctreeBlock;
  15390. })(BABYLON || (BABYLON = {}));
  15391. //# sourceMappingURL=babylon.octreeBlock.js.map
  15392. var BABYLON;
  15393. (function (BABYLON) {
  15394. var Bone = (function () {
  15395. function Bone(name, skeleton, parentBone, matrix) {
  15396. this.name = name;
  15397. this.children = new Array();
  15398. this.animations = new Array();
  15399. this._worldTransform = new BABYLON.Matrix();
  15400. this._absoluteTransform = new BABYLON.Matrix();
  15401. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15402. this._skeleton = skeleton;
  15403. this._matrix = matrix;
  15404. this._baseMatrix = matrix;
  15405. skeleton.bones.push(this);
  15406. if (parentBone) {
  15407. this._parent = parentBone;
  15408. parentBone.children.push(this);
  15409. } else {
  15410. this._parent = null;
  15411. }
  15412. this._updateDifferenceMatrix();
  15413. }
  15414. // Members
  15415. Bone.prototype.getParent = function () {
  15416. return this._parent;
  15417. };
  15418. Bone.prototype.getLocalMatrix = function () {
  15419. return this._matrix;
  15420. };
  15421. Bone.prototype.getBaseMatrix = function () {
  15422. return this._baseMatrix;
  15423. };
  15424. Bone.prototype.getWorldMatrix = function () {
  15425. return this._worldTransform;
  15426. };
  15427. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15428. return this._invertedAbsoluteTransform;
  15429. };
  15430. Bone.prototype.getAbsoluteMatrix = function () {
  15431. var matrix = this._matrix.clone();
  15432. var parent = this._parent;
  15433. while (parent) {
  15434. matrix = matrix.multiply(parent.getLocalMatrix());
  15435. parent = parent.getParent();
  15436. }
  15437. return matrix;
  15438. };
  15439. // Methods
  15440. Bone.prototype.updateMatrix = function (matrix) {
  15441. this._matrix = matrix;
  15442. this._skeleton._markAsDirty();
  15443. this._updateDifferenceMatrix();
  15444. };
  15445. Bone.prototype._updateDifferenceMatrix = function () {
  15446. if (this._parent) {
  15447. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15448. } else {
  15449. this._absoluteTransform.copyFrom(this._matrix);
  15450. }
  15451. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15452. for (var index = 0; index < this.children.length; index++) {
  15453. this.children[index]._updateDifferenceMatrix();
  15454. }
  15455. };
  15456. Bone.prototype.markAsDirty = function () {
  15457. this._skeleton._markAsDirty();
  15458. };
  15459. return Bone;
  15460. })();
  15461. BABYLON.Bone = Bone;
  15462. })(BABYLON || (BABYLON = {}));
  15463. //# sourceMappingURL=babylon.bone.js.map
  15464. var BABYLON;
  15465. (function (BABYLON) {
  15466. var Skeleton = (function () {
  15467. function Skeleton(name, id, scene) {
  15468. this.name = name;
  15469. this.id = id;
  15470. this.bones = new Array();
  15471. this._isDirty = true;
  15472. this._identity = BABYLON.Matrix.Identity();
  15473. this.bones = [];
  15474. this._scene = scene;
  15475. scene.skeletons.push(this);
  15476. }
  15477. // Members
  15478. Skeleton.prototype.getTransformMatrices = function () {
  15479. return this._transformMatrices;
  15480. };
  15481. // Methods
  15482. Skeleton.prototype._markAsDirty = function () {
  15483. this._isDirty = true;
  15484. };
  15485. Skeleton.prototype.prepare = function () {
  15486. if (!this._isDirty) {
  15487. return;
  15488. }
  15489. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  15490. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  15491. }
  15492. for (var index = 0; index < this.bones.length; index++) {
  15493. var bone = this.bones[index];
  15494. var parentBone = bone.getParent();
  15495. if (parentBone) {
  15496. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  15497. } else {
  15498. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  15499. }
  15500. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  15501. }
  15502. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  15503. this._isDirty = false;
  15504. };
  15505. Skeleton.prototype.getAnimatables = function () {
  15506. if (!this._animatables || this._animatables.length != this.bones.length) {
  15507. this._animatables = [];
  15508. for (var index = 0; index < this.bones.length; index++) {
  15509. this._animatables.push(this.bones[index]);
  15510. }
  15511. }
  15512. return this._animatables;
  15513. };
  15514. Skeleton.prototype.clone = function (name, id) {
  15515. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  15516. for (var index = 0; index < this.bones.length; index++) {
  15517. var source = this.bones[index];
  15518. var parentBone = null;
  15519. if (source.getParent()) {
  15520. var parentIndex = this.bones.indexOf(source.getParent());
  15521. parentBone = result.bones[parentIndex];
  15522. }
  15523. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  15524. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  15525. }
  15526. return result;
  15527. };
  15528. return Skeleton;
  15529. })();
  15530. BABYLON.Skeleton = Skeleton;
  15531. })(BABYLON || (BABYLON = {}));
  15532. //# sourceMappingURL=babylon.skeleton.js.map
  15533. var BABYLON;
  15534. (function (BABYLON) {
  15535. var PostProcess = (function () {
  15536. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  15537. this.name = name;
  15538. this.width = -1;
  15539. this.height = -1;
  15540. this._reusable = false;
  15541. this._textures = new BABYLON.SmartArray(2);
  15542. this._currentRenderTextureInd = 0;
  15543. if (camera != null) {
  15544. this._camera = camera;
  15545. this._scene = camera.getScene();
  15546. camera.attachPostProcess(this);
  15547. this._engine = this._scene.getEngine();
  15548. } else {
  15549. this._engine = engine;
  15550. }
  15551. this._renderRatio = ratio;
  15552. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15553. this._reusable = reusable || false;
  15554. samplers = samplers || [];
  15555. samplers.push("textureSampler");
  15556. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  15557. }
  15558. PostProcess.prototype.isReusable = function () {
  15559. return this._reusable;
  15560. };
  15561. PostProcess.prototype.activate = function (camera, sourceTexture) {
  15562. camera = camera || this._camera;
  15563. var scene = camera.getScene();
  15564. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  15565. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  15566. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  15567. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  15568. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  15569. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  15570. if (this._textures.length > 0) {
  15571. for (var i = 0; i < this._textures.length; i++) {
  15572. this._engine._releaseTexture(this._textures.data[i]);
  15573. }
  15574. this._textures.reset();
  15575. }
  15576. this.width = desiredWidth;
  15577. this.height = desiredHeight;
  15578. 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 }));
  15579. if (this._reusable) {
  15580. 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 }));
  15581. }
  15582. if (this.onSizeChanged) {
  15583. this.onSizeChanged();
  15584. }
  15585. }
  15586. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  15587. if (this.onActivate) {
  15588. this.onActivate(camera);
  15589. }
  15590. // Clear
  15591. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  15592. if (this._reusable) {
  15593. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  15594. }
  15595. };
  15596. PostProcess.prototype.apply = function () {
  15597. // Check
  15598. if (!this._effect.isReady())
  15599. return null;
  15600. // States
  15601. this._engine.enableEffect(this._effect);
  15602. this._engine.setState(false);
  15603. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15604. this._engine.setDepthBuffer(false);
  15605. this._engine.setDepthWrite(false);
  15606. // Texture
  15607. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  15608. // Parameters
  15609. if (this.onApply) {
  15610. this.onApply(this._effect);
  15611. }
  15612. return this._effect;
  15613. };
  15614. PostProcess.prototype.dispose = function (camera) {
  15615. camera = camera || this._camera;
  15616. if (this._textures.length > 0) {
  15617. for (var i = 0; i < this._textures.length; i++) {
  15618. this._engine._releaseTexture(this._textures.data[i]);
  15619. }
  15620. this._textures.reset();
  15621. }
  15622. camera.detachPostProcess(this);
  15623. var index = camera._postProcesses.indexOf(this);
  15624. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  15625. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  15626. }
  15627. };
  15628. return PostProcess;
  15629. })();
  15630. BABYLON.PostProcess = PostProcess;
  15631. })(BABYLON || (BABYLON = {}));
  15632. //# sourceMappingURL=babylon.postProcess.js.map
  15633. var BABYLON;
  15634. (function (BABYLON) {
  15635. var PostProcessManager = (function () {
  15636. function PostProcessManager(scene) {
  15637. this._vertexDeclaration = [2];
  15638. this._vertexStrideSize = 2 * 4;
  15639. this._scene = scene;
  15640. // VBO
  15641. var vertices = [];
  15642. vertices.push(1, 1);
  15643. vertices.push(-1, 1);
  15644. vertices.push(-1, -1);
  15645. vertices.push(1, -1);
  15646. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15647. // Indices
  15648. var indices = [];
  15649. indices.push(0);
  15650. indices.push(1);
  15651. indices.push(2);
  15652. indices.push(0);
  15653. indices.push(2);
  15654. indices.push(3);
  15655. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15656. }
  15657. // Methods
  15658. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  15659. var postProcesses = this._scene.activeCamera._postProcesses;
  15660. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15661. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15662. return false;
  15663. }
  15664. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  15665. return true;
  15666. };
  15667. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  15668. var postProcesses = this._scene.activeCamera._postProcesses;
  15669. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15670. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15671. return;
  15672. }
  15673. var engine = this._scene.getEngine();
  15674. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  15675. if (index < postProcessesTakenIndices.length - 1) {
  15676. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  15677. } else {
  15678. if (targetTexture) {
  15679. engine.bindFramebuffer(targetTexture);
  15680. } else {
  15681. engine.restoreDefaultFramebuffer();
  15682. }
  15683. }
  15684. if (doNotPresent) {
  15685. break;
  15686. }
  15687. var pp = postProcesses[postProcessesTakenIndices[index]];
  15688. var effect = pp.apply();
  15689. if (effect) {
  15690. if (pp.onBeforeRender) {
  15691. pp.onBeforeRender(effect);
  15692. }
  15693. // VBOs
  15694. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15695. // Draw order
  15696. engine.draw(true, 0, 6);
  15697. }
  15698. }
  15699. // Restore depth buffer
  15700. engine.setDepthBuffer(true);
  15701. engine.setDepthWrite(true);
  15702. };
  15703. PostProcessManager.prototype.dispose = function () {
  15704. if (this._vertexBuffer) {
  15705. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15706. this._vertexBuffer = null;
  15707. }
  15708. if (this._indexBuffer) {
  15709. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15710. this._indexBuffer = null;
  15711. }
  15712. };
  15713. return PostProcessManager;
  15714. })();
  15715. BABYLON.PostProcessManager = PostProcessManager;
  15716. })(BABYLON || (BABYLON = {}));
  15717. //# sourceMappingURL=babylon.postProcessManager.js.map
  15718. var BABYLON;
  15719. (function (BABYLON) {
  15720. var PassPostProcess = (function (_super) {
  15721. __extends(PassPostProcess, _super);
  15722. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15723. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  15724. }
  15725. return PassPostProcess;
  15726. })(BABYLON.PostProcess);
  15727. BABYLON.PassPostProcess = PassPostProcess;
  15728. })(BABYLON || (BABYLON = {}));
  15729. //# sourceMappingURL=babylon.passPostProcess.js.map
  15730. var BABYLON;
  15731. (function (BABYLON) {
  15732. var BlurPostProcess = (function (_super) {
  15733. __extends(BlurPostProcess, _super);
  15734. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  15735. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  15736. var _this = this;
  15737. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  15738. this.direction = direction;
  15739. this.blurWidth = blurWidth;
  15740. this.onApply = function (effect) {
  15741. effect.setFloat2("screenSize", _this.width, _this.height);
  15742. effect.setVector2("direction", _this.direction);
  15743. effect.setFloat("blurWidth", _this.blurWidth);
  15744. };
  15745. }
  15746. return BlurPostProcess;
  15747. })(BABYLON.PostProcess);
  15748. BABYLON.BlurPostProcess = BlurPostProcess;
  15749. })(BABYLON || (BABYLON = {}));
  15750. //# sourceMappingURL=babylon.blurPostProcess.js.map
  15751. var BABYLON;
  15752. (function (BABYLON) {
  15753. var FilterPostProcess = (function (_super) {
  15754. __extends(FilterPostProcess, _super);
  15755. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  15756. var _this = this;
  15757. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  15758. this.kernelMatrix = kernelMatrix;
  15759. this.onApply = function (effect) {
  15760. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  15761. };
  15762. }
  15763. return FilterPostProcess;
  15764. })(BABYLON.PostProcess);
  15765. BABYLON.FilterPostProcess = FilterPostProcess;
  15766. })(BABYLON || (BABYLON = {}));
  15767. //# sourceMappingURL=babylon.filterPostProcess.js.map
  15768. var BABYLON;
  15769. (function (BABYLON) {
  15770. var RefractionPostProcess = (function (_super) {
  15771. __extends(RefractionPostProcess, _super);
  15772. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  15773. var _this = this;
  15774. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  15775. this.color = color;
  15776. this.depth = depth;
  15777. this.colorLevel = colorLevel;
  15778. this.onActivate = function (cam) {
  15779. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  15780. };
  15781. this.onApply = function (effect) {
  15782. effect.setColor3("baseColor", _this.color);
  15783. effect.setFloat("depth", _this.depth);
  15784. effect.setFloat("colorLevel", _this.colorLevel);
  15785. effect.setTexture("refractionSampler", _this._refRexture);
  15786. };
  15787. }
  15788. // Methods
  15789. RefractionPostProcess.prototype.dispose = function (camera) {
  15790. if (this._refRexture) {
  15791. this._refRexture.dispose();
  15792. }
  15793. _super.prototype.dispose.call(this, camera);
  15794. };
  15795. return RefractionPostProcess;
  15796. })(BABYLON.PostProcess);
  15797. BABYLON.RefractionPostProcess = RefractionPostProcess;
  15798. })(BABYLON || (BABYLON = {}));
  15799. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  15800. var BABYLON;
  15801. (function (BABYLON) {
  15802. var BlackAndWhitePostProcess = (function (_super) {
  15803. __extends(BlackAndWhitePostProcess, _super);
  15804. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15805. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  15806. }
  15807. return BlackAndWhitePostProcess;
  15808. })(BABYLON.PostProcess);
  15809. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  15810. })(BABYLON || (BABYLON = {}));
  15811. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  15812. var BABYLON;
  15813. (function (BABYLON) {
  15814. var ConvolutionPostProcess = (function (_super) {
  15815. __extends(ConvolutionPostProcess, _super);
  15816. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  15817. var _this = this;
  15818. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  15819. this.kernel = kernel;
  15820. this.onApply = function (effect) {
  15821. effect.setFloat2("screenSize", _this.width, _this.height);
  15822. effect.setArray("kernel", _this.kernel);
  15823. };
  15824. }
  15825. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  15826. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  15827. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  15828. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  15829. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  15830. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  15831. return ConvolutionPostProcess;
  15832. })(BABYLON.PostProcess);
  15833. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  15834. })(BABYLON || (BABYLON = {}));
  15835. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  15836. var BABYLON;
  15837. (function (BABYLON) {
  15838. var FxaaPostProcess = (function (_super) {
  15839. __extends(FxaaPostProcess, _super);
  15840. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15841. var _this = this;
  15842. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  15843. this.onSizeChanged = function () {
  15844. _this.texelWidth = 1.0 / _this.width;
  15845. _this.texelHeight = 1.0 / _this.height;
  15846. };
  15847. this.onApply = function (effect) {
  15848. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  15849. };
  15850. }
  15851. return FxaaPostProcess;
  15852. })(BABYLON.PostProcess);
  15853. BABYLON.FxaaPostProcess = FxaaPostProcess;
  15854. })(BABYLON || (BABYLON = {}));
  15855. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  15856. var BABYLON;
  15857. (function (BABYLON) {
  15858. var LensFlare = (function () {
  15859. function LensFlare(size, position, color, imgUrl, system) {
  15860. this.size = size;
  15861. this.position = position;
  15862. this.dispose = function () {
  15863. if (this.texture) {
  15864. this.texture.dispose();
  15865. }
  15866. // Remove from scene
  15867. var index = this._system.lensFlares.indexOf(this);
  15868. this._system.lensFlares.splice(index, 1);
  15869. };
  15870. this.color = color || new BABYLON.Color3(1, 1, 1);
  15871. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  15872. this._system = system;
  15873. system.lensFlares.push(this);
  15874. }
  15875. return LensFlare;
  15876. })();
  15877. BABYLON.LensFlare = LensFlare;
  15878. })(BABYLON || (BABYLON = {}));
  15879. //# sourceMappingURL=babylon.lensFlare.js.map
  15880. var BABYLON;
  15881. (function (BABYLON) {
  15882. var LensFlareSystem = (function () {
  15883. function LensFlareSystem(name, emitter, scene) {
  15884. this.name = name;
  15885. this.lensFlares = new Array();
  15886. this.borderLimit = 300;
  15887. this._vertexDeclaration = [2];
  15888. this._vertexStrideSize = 2 * 4;
  15889. this._isEnabled = true;
  15890. this._scene = scene;
  15891. this._emitter = emitter;
  15892. scene.lensFlareSystems.push(this);
  15893. this.meshesSelectionPredicate = function (m) {
  15894. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  15895. };
  15896. // VBO
  15897. var vertices = [];
  15898. vertices.push(1, 1);
  15899. vertices.push(-1, 1);
  15900. vertices.push(-1, -1);
  15901. vertices.push(1, -1);
  15902. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15903. // Indices
  15904. var indices = [];
  15905. indices.push(0);
  15906. indices.push(1);
  15907. indices.push(2);
  15908. indices.push(0);
  15909. indices.push(2);
  15910. indices.push(3);
  15911. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15912. // Effects
  15913. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  15914. }
  15915. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  15916. get: function () {
  15917. return this._isEnabled;
  15918. },
  15919. set: function (value) {
  15920. this._isEnabled = value;
  15921. },
  15922. enumerable: true,
  15923. configurable: true
  15924. });
  15925. LensFlareSystem.prototype.getScene = function () {
  15926. return this._scene;
  15927. };
  15928. LensFlareSystem.prototype.getEmitter = function () {
  15929. return this._emitter;
  15930. };
  15931. LensFlareSystem.prototype.getEmitterPosition = function () {
  15932. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  15933. };
  15934. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  15935. var position = this.getEmitterPosition();
  15936. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  15937. this._positionX = position.x;
  15938. this._positionY = position.y;
  15939. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  15940. if (position.z > 0) {
  15941. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  15942. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  15943. return true;
  15944. }
  15945. }
  15946. return false;
  15947. };
  15948. LensFlareSystem.prototype._isVisible = function () {
  15949. if (!this._isEnabled) {
  15950. return false;
  15951. }
  15952. var emitterPosition = this.getEmitterPosition();
  15953. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  15954. var distance = direction.length();
  15955. direction.normalize();
  15956. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  15957. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  15958. return !pickInfo.hit || pickInfo.distance > distance;
  15959. };
  15960. LensFlareSystem.prototype.render = function () {
  15961. if (!this._effect.isReady())
  15962. return false;
  15963. var engine = this._scene.getEngine();
  15964. var viewport = this._scene.activeCamera.viewport;
  15965. var globalViewport = viewport.toGlobal(engine);
  15966. // Position
  15967. if (!this.computeEffectivePosition(globalViewport)) {
  15968. return false;
  15969. }
  15970. // Visibility
  15971. if (!this._isVisible()) {
  15972. return false;
  15973. }
  15974. // Intensity
  15975. var awayX;
  15976. var awayY;
  15977. if (this._positionX < this.borderLimit + globalViewport.x) {
  15978. awayX = this.borderLimit + globalViewport.x - this._positionX;
  15979. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  15980. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  15981. } else {
  15982. awayX = 0;
  15983. }
  15984. if (this._positionY < this.borderLimit + globalViewport.y) {
  15985. awayY = this.borderLimit + globalViewport.y - this._positionY;
  15986. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  15987. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  15988. } else {
  15989. awayY = 0;
  15990. }
  15991. var away = (awayX > awayY) ? awayX : awayY;
  15992. if (away > this.borderLimit) {
  15993. away = this.borderLimit;
  15994. }
  15995. var intensity = 1.0 - (away / this.borderLimit);
  15996. if (intensity < 0) {
  15997. return false;
  15998. }
  15999. if (intensity > 1.0) {
  16000. intensity = 1.0;
  16001. }
  16002. // Position
  16003. var centerX = globalViewport.x + globalViewport.width / 2;
  16004. var centerY = globalViewport.y + globalViewport.height / 2;
  16005. var distX = centerX - this._positionX;
  16006. var distY = centerY - this._positionY;
  16007. // Effects
  16008. engine.enableEffect(this._effect);
  16009. engine.setState(false);
  16010. engine.setDepthBuffer(false);
  16011. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16012. // VBOs
  16013. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16014. for (var index = 0; index < this.lensFlares.length; index++) {
  16015. var flare = this.lensFlares[index];
  16016. var x = centerX - (distX * flare.position);
  16017. var y = centerY - (distY * flare.position);
  16018. var cw = flare.size;
  16019. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16020. var cx = 2 * (x / globalViewport.width) - 1.0;
  16021. var cy = 1.0 - 2 * (y / globalViewport.height);
  16022. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16023. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16024. // Texture
  16025. this._effect.setTexture("textureSampler", flare.texture);
  16026. // Color
  16027. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16028. // Draw order
  16029. engine.draw(true, 0, 6);
  16030. }
  16031. engine.setDepthBuffer(true);
  16032. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16033. return true;
  16034. };
  16035. LensFlareSystem.prototype.dispose = function () {
  16036. if (this._vertexBuffer) {
  16037. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16038. this._vertexBuffer = null;
  16039. }
  16040. if (this._indexBuffer) {
  16041. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16042. this._indexBuffer = null;
  16043. }
  16044. while (this.lensFlares.length) {
  16045. this.lensFlares[0].dispose();
  16046. }
  16047. // Remove from scene
  16048. var index = this._scene.lensFlareSystems.indexOf(this);
  16049. this._scene.lensFlareSystems.splice(index, 1);
  16050. };
  16051. return LensFlareSystem;
  16052. })();
  16053. BABYLON.LensFlareSystem = LensFlareSystem;
  16054. })(BABYLON || (BABYLON = {}));
  16055. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  16056. var BABYLON;
  16057. (function (BABYLON) {
  16058. var IntersectionInfo = (function () {
  16059. function IntersectionInfo(bu, bv, distance) {
  16060. this.bu = bu;
  16061. this.bv = bv;
  16062. this.distance = distance;
  16063. this.faceId = 0;
  16064. }
  16065. return IntersectionInfo;
  16066. })();
  16067. BABYLON.IntersectionInfo = IntersectionInfo;
  16068. var PickingInfo = (function () {
  16069. function PickingInfo() {
  16070. this.hit = false;
  16071. this.distance = 0;
  16072. this.pickedPoint = null;
  16073. this.pickedMesh = null;
  16074. this.bu = 0;
  16075. this.bv = 0;
  16076. this.faceId = -1;
  16077. }
  16078. // Methods
  16079. PickingInfo.prototype.getNormal = function () {
  16080. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16081. return null;
  16082. }
  16083. var indices = this.pickedMesh.getIndices();
  16084. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16085. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16086. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16087. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16088. normal0 = normal0.scale(this.bu);
  16089. normal1 = normal1.scale(this.bv);
  16090. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16091. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16092. };
  16093. PickingInfo.prototype.getTextureCoordinates = function () {
  16094. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16095. return null;
  16096. }
  16097. var indices = this.pickedMesh.getIndices();
  16098. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16099. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16100. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16101. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16102. uv0 = uv0.scale(this.bu);
  16103. uv1 = uv1.scale(this.bv);
  16104. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16105. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16106. };
  16107. return PickingInfo;
  16108. })();
  16109. BABYLON.PickingInfo = PickingInfo;
  16110. })(BABYLON || (BABYLON = {}));
  16111. //# sourceMappingURL=babylon.pickingInfo.js.map
  16112. var BABYLON;
  16113. (function (BABYLON) {
  16114. var FilesInput = (function () {
  16115. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16116. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16117. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16118. this.engine = p_engine;
  16119. this.canvas = p_canvas;
  16120. this.currentScene = p_scene;
  16121. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16122. this.progressCallback = p_progressCallback;
  16123. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16124. this.textureLoadingCallback = p_textureLoadingCallback;
  16125. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16126. }
  16127. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16128. var _this = this;
  16129. if (p_elementToMonitor) {
  16130. this.elementToMonitor = p_elementToMonitor;
  16131. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16132. _this.drag(e);
  16133. }, false);
  16134. this.elementToMonitor.addEventListener("dragover", function (e) {
  16135. _this.drag(e);
  16136. }, false);
  16137. this.elementToMonitor.addEventListener("drop", function (e) {
  16138. _this.drop(e);
  16139. }, false);
  16140. }
  16141. };
  16142. FilesInput.prototype.renderFunction = function () {
  16143. if (this.additionnalRenderLoopLogicCallback) {
  16144. this.additionnalRenderLoopLogicCallback();
  16145. }
  16146. if (this.currentScene) {
  16147. if (this.textureLoadingCallback) {
  16148. var remaining = this.currentScene.getWaitingItemsCount();
  16149. if (remaining > 0) {
  16150. this.textureLoadingCallback(remaining);
  16151. }
  16152. }
  16153. this.currentScene.render();
  16154. }
  16155. };
  16156. FilesInput.prototype.drag = function (e) {
  16157. e.stopPropagation();
  16158. e.preventDefault();
  16159. };
  16160. FilesInput.prototype.drop = function (eventDrop) {
  16161. eventDrop.stopPropagation();
  16162. eventDrop.preventDefault();
  16163. this.loadFiles(eventDrop);
  16164. };
  16165. FilesInput.prototype.loadFiles = function (event) {
  16166. var _this = this;
  16167. var that = this;
  16168. if (this.startingProcessingFilesCallback)
  16169. this.startingProcessingFilesCallback();
  16170. var sceneFileToLoad;
  16171. var filesToLoad;
  16172. // Handling data transfer via drag'n'drop
  16173. if (event && event.dataTransfer && event.dataTransfer.files) {
  16174. filesToLoad = event.dataTransfer.files;
  16175. }
  16176. // Handling files from input files
  16177. if (event && event.target && event.target.files) {
  16178. filesToLoad = event.target.files;
  16179. }
  16180. if (filesToLoad && filesToLoad.length > 0) {
  16181. for (var i = 0; i < filesToLoad.length; i++) {
  16182. switch (filesToLoad[i].type) {
  16183. case "image/jpeg":
  16184. case "image/png":
  16185. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16186. break;
  16187. case "image/targa":
  16188. case "image/vnd.ms-dds":
  16189. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16190. break;
  16191. default:
  16192. if (filesToLoad[i].name.indexOf(".babylon") !== -1 && filesToLoad[i].name.indexOf(".manifest") === -1 && filesToLoad[i].name.indexOf(".incremental") === -1 && filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  16193. sceneFileToLoad = filesToLoad[i];
  16194. }
  16195. break;
  16196. }
  16197. }
  16198. // If a ".babylon" file has been provided
  16199. if (sceneFileToLoad) {
  16200. if (this.currentScene) {
  16201. this.engine.stopRenderLoop();
  16202. this.currentScene.dispose();
  16203. }
  16204. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16205. that.currentScene = newScene;
  16206. // Wait for textures and shaders to be ready
  16207. that.currentScene.executeWhenReady(function () {
  16208. // Attach camera to canvas inputs
  16209. if (that.currentScene.activeCamera) {
  16210. that.currentScene.activeCamera.attachControl(that.canvas);
  16211. }
  16212. if (that.sceneLoadedCallback) {
  16213. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16214. }
  16215. that.engine.runRenderLoop(function () {
  16216. that.renderFunction();
  16217. });
  16218. });
  16219. }, function (progress) {
  16220. if (_this.progressCallback) {
  16221. _this.progressCallback(progress);
  16222. }
  16223. });
  16224. } else {
  16225. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  16226. }
  16227. }
  16228. };
  16229. FilesInput.FilesTextures = new Array();
  16230. FilesInput.FilesToLoad = new Array();
  16231. return FilesInput;
  16232. })();
  16233. BABYLON.FilesInput = FilesInput;
  16234. })(BABYLON || (BABYLON = {}));
  16235. //# sourceMappingURL=babylon.filesInput.js.map
  16236. var BABYLON;
  16237. (function (BABYLON) {
  16238. var OimoJSPlugin = (function () {
  16239. function OimoJSPlugin() {
  16240. this._registeredMeshes = [];
  16241. /**
  16242. * Update the body position according to the mesh position
  16243. * @param mesh
  16244. */
  16245. this.updateBodyPosition = function (mesh) {
  16246. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16247. var registeredMesh = this._registeredMeshes[index];
  16248. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16249. var body = registeredMesh.body.body;
  16250. mesh.computeWorldMatrix(true);
  16251. var center = mesh.getBoundingInfo().boundingBox.center;
  16252. body.setPosition(center.x, center.y, center.z);
  16253. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  16254. return;
  16255. }
  16256. // Case where the parent has been updated
  16257. if (registeredMesh.mesh.parent === mesh) {
  16258. mesh.computeWorldMatrix(true);
  16259. registeredMesh.mesh.computeWorldMatrix(true);
  16260. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  16261. var absoluteRotation = mesh.rotation;
  16262. body = registeredMesh.body.body;
  16263. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  16264. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  16265. return;
  16266. }
  16267. }
  16268. };
  16269. }
  16270. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  16271. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16272. };
  16273. OimoJSPlugin.prototype.initialize = function (iterations) {
  16274. this._world = new OIMO.World();
  16275. this._world.clear();
  16276. };
  16277. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16278. this._world.gravity = gravity;
  16279. };
  16280. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16281. var body = null;
  16282. this.unregisterMesh(mesh);
  16283. mesh.computeWorldMatrix(true);
  16284. switch (impostor) {
  16285. case BABYLON.PhysicsEngine.SphereImpostor:
  16286. var initialRotation = null;
  16287. if (mesh.rotationQuaternion) {
  16288. initialRotation = mesh.rotationQuaternion.clone();
  16289. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16290. mesh.computeWorldMatrix(true);
  16291. }
  16292. var bbox = mesh.getBoundingInfo().boundingBox;
  16293. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16294. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16295. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16296. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16297. // The delta between the mesh position and the mesh bounding box center
  16298. var deltaPosition = mesh.position.subtract(bbox.center);
  16299. // Transform delta position with the rotation
  16300. if (initialRotation) {
  16301. var m = new BABYLON.Matrix();
  16302. initialRotation.toRotationMatrix(m);
  16303. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16304. }
  16305. body = new OIMO.Body({
  16306. type: 'sphere',
  16307. size: [size],
  16308. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16309. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16310. move: options.mass != 0,
  16311. config: [options.mass, options.friction, options.restitution],
  16312. world: this._world
  16313. });
  16314. // Restore rotation
  16315. if (initialRotation) {
  16316. body.setQuaternion(initialRotation);
  16317. }
  16318. this._registeredMeshes.push({
  16319. mesh: mesh,
  16320. body: body,
  16321. delta: deltaPosition
  16322. });
  16323. break;
  16324. case BABYLON.PhysicsEngine.PlaneImpostor:
  16325. case BABYLON.PhysicsEngine.BoxImpostor:
  16326. initialRotation = null;
  16327. if (mesh.rotationQuaternion) {
  16328. initialRotation = mesh.rotationQuaternion.clone();
  16329. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16330. mesh.computeWorldMatrix(true);
  16331. }
  16332. bbox = mesh.getBoundingInfo().boundingBox;
  16333. var min = bbox.minimumWorld;
  16334. var max = bbox.maximumWorld;
  16335. var box = max.subtract(min);
  16336. var sizeX = this._checkWithEpsilon(box.x);
  16337. var sizeY = this._checkWithEpsilon(box.y);
  16338. var sizeZ = this._checkWithEpsilon(box.z);
  16339. // The delta between the mesh position and the mesh boudning box center
  16340. deltaPosition = mesh.position.subtract(bbox.center);
  16341. // Transform delta position with the rotation
  16342. if (initialRotation) {
  16343. m = new BABYLON.Matrix();
  16344. initialRotation.toRotationMatrix(m);
  16345. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16346. }
  16347. body = new OIMO.Body({
  16348. type: 'box',
  16349. size: [sizeX, sizeY, sizeZ],
  16350. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16351. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16352. move: options.mass != 0,
  16353. config: [options.mass, options.friction, options.restitution],
  16354. world: this._world
  16355. });
  16356. if (initialRotation) {
  16357. body.setQuaternion(initialRotation);
  16358. }
  16359. this._registeredMeshes.push({
  16360. mesh: mesh,
  16361. body: body,
  16362. delta: deltaPosition
  16363. });
  16364. break;
  16365. }
  16366. return body;
  16367. };
  16368. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16369. var types = [], sizes = [], positions = [], rotations = [];
  16370. var initialMesh = parts[0].mesh;
  16371. for (var index = 0; index < parts.length; index++) {
  16372. var part = parts[index];
  16373. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16374. types.push(bodyParameters.type);
  16375. sizes.push.apply(sizes, bodyParameters.size);
  16376. positions.push.apply(positions, bodyParameters.pos);
  16377. rotations.push.apply(rotations, bodyParameters.rot);
  16378. }
  16379. var body = new OIMO.Body({
  16380. type: types,
  16381. size: sizes,
  16382. pos: positions,
  16383. rot: rotations,
  16384. move: options.mass != 0,
  16385. config: [options.mass, options.friction, options.restitution],
  16386. world: this._world
  16387. });
  16388. this._registeredMeshes.push({
  16389. mesh: initialMesh,
  16390. body: body
  16391. });
  16392. return body;
  16393. };
  16394. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16395. var bodyParameters = null;
  16396. var mesh = part.mesh;
  16397. switch (part.impostor) {
  16398. case BABYLON.PhysicsEngine.SphereImpostor:
  16399. var bbox = mesh.getBoundingInfo().boundingBox;
  16400. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16401. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16402. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16403. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16404. bodyParameters = {
  16405. type: 'sphere',
  16406. /* bug with oimo : sphere needs 3 sizes in this case */
  16407. size: [size, -1, -1],
  16408. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  16409. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16410. };
  16411. break;
  16412. case BABYLON.PhysicsEngine.PlaneImpostor:
  16413. case BABYLON.PhysicsEngine.BoxImpostor:
  16414. bbox = mesh.getBoundingInfo().boundingBox;
  16415. var min = bbox.minimumWorld;
  16416. var max = bbox.maximumWorld;
  16417. var box = max.subtract(min);
  16418. var sizeX = this._checkWithEpsilon(box.x);
  16419. var sizeY = this._checkWithEpsilon(box.y);
  16420. var sizeZ = this._checkWithEpsilon(box.z);
  16421. var relativePosition = mesh.position;
  16422. bodyParameters = {
  16423. type: 'box',
  16424. size: [sizeX, sizeY, sizeZ],
  16425. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16426. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16427. };
  16428. break;
  16429. }
  16430. return bodyParameters;
  16431. };
  16432. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16433. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16434. var registeredMesh = this._registeredMeshes[index];
  16435. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16436. if (registeredMesh.body) {
  16437. this._world.removeRigidBody(registeredMesh.body.body);
  16438. this._unbindBody(registeredMesh.body);
  16439. }
  16440. this._registeredMeshes.splice(index, 1);
  16441. return;
  16442. }
  16443. }
  16444. };
  16445. OimoJSPlugin.prototype._unbindBody = function (body) {
  16446. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16447. var registeredMesh = this._registeredMeshes[index];
  16448. if (registeredMesh.body === body) {
  16449. registeredMesh.body = null;
  16450. }
  16451. }
  16452. };
  16453. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  16454. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16455. var registeredMesh = this._registeredMeshes[index];
  16456. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16457. // Get object mass to have a behaviour similar to cannon.js
  16458. var mass = registeredMesh.body.body.massInfo.mass;
  16459. // The force is scaled with the mass of object
  16460. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  16461. return;
  16462. }
  16463. }
  16464. };
  16465. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16466. var body1 = null, body2 = null;
  16467. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16468. var registeredMesh = this._registeredMeshes[index];
  16469. if (registeredMesh.mesh === mesh1) {
  16470. body1 = registeredMesh.body.body;
  16471. } else if (registeredMesh.mesh === mesh2) {
  16472. body2 = registeredMesh.body.body;
  16473. }
  16474. }
  16475. if (!body1 || !body2) {
  16476. return false;
  16477. }
  16478. if (!options) {
  16479. options = {};
  16480. }
  16481. new OIMO.Link({
  16482. type: options.type,
  16483. body1: body1,
  16484. body2: body2,
  16485. min: options.min,
  16486. max: options.max,
  16487. axe1: options.axe1,
  16488. axe2: options.axe2,
  16489. pos1: [pivot1.x, pivot1.y, pivot1.z],
  16490. pos2: [pivot2.x, pivot2.y, pivot2.z],
  16491. collision: options.collision,
  16492. spring: options.spring,
  16493. world: this._world
  16494. });
  16495. return true;
  16496. };
  16497. OimoJSPlugin.prototype.dispose = function () {
  16498. this._world.clear();
  16499. while (this._registeredMeshes.length) {
  16500. this.unregisterMesh(this._registeredMeshes[0].mesh);
  16501. }
  16502. };
  16503. OimoJSPlugin.prototype.isSupported = function () {
  16504. return OIMO !== undefined;
  16505. };
  16506. OimoJSPlugin.prototype._getLastShape = function (body) {
  16507. var lastShape = body.shapes;
  16508. while (lastShape.next) {
  16509. lastShape = lastShape.next;
  16510. }
  16511. return lastShape;
  16512. };
  16513. OimoJSPlugin.prototype.runOneStep = function (time) {
  16514. this._world.step();
  16515. // Update the position of all registered meshes
  16516. var i = this._registeredMeshes.length;
  16517. var m;
  16518. while (i--) {
  16519. var body = this._registeredMeshes[i].body.body;
  16520. var mesh = this._registeredMeshes[i].mesh;
  16521. var delta = this._registeredMeshes[i].delta;
  16522. if (!body.sleeping) {
  16523. if (body.shapes.next) {
  16524. var parentShape = this._getLastShape(body);
  16525. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  16526. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  16527. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  16528. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  16529. if (!mesh.rotationQuaternion) {
  16530. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16531. }
  16532. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16533. mesh.computeWorldMatrix();
  16534. } else {
  16535. m = body.getMatrix();
  16536. mtx = BABYLON.Matrix.FromArray(m);
  16537. // Body position
  16538. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  16539. if (!delta) {
  16540. mesh.position.x = bodyX;
  16541. mesh.position.y = bodyY;
  16542. mesh.position.z = bodyZ;
  16543. } else {
  16544. mesh.position.x = bodyX + delta.x;
  16545. mesh.position.y = bodyY + delta.y;
  16546. mesh.position.z = bodyZ + delta.z;
  16547. }
  16548. if (!mesh.rotationQuaternion) {
  16549. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16550. }
  16551. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16552. mesh.computeWorldMatrix();
  16553. }
  16554. }
  16555. }
  16556. };
  16557. return OimoJSPlugin;
  16558. })();
  16559. BABYLON.OimoJSPlugin = OimoJSPlugin;
  16560. })(BABYLON || (BABYLON = {}));
  16561. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  16562. var BABYLON;
  16563. (function (BABYLON) {
  16564. var PhysicsEngine = (function () {
  16565. function PhysicsEngine(plugin) {
  16566. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  16567. }
  16568. PhysicsEngine.prototype._initialize = function (gravity) {
  16569. this._currentPlugin.initialize();
  16570. this._setGravity(gravity);
  16571. };
  16572. PhysicsEngine.prototype._runOneStep = function (delta) {
  16573. if (delta > 0.1) {
  16574. delta = 0.1;
  16575. } else if (delta <= 0) {
  16576. delta = 1.0 / 60.0;
  16577. }
  16578. this._currentPlugin.runOneStep(delta);
  16579. };
  16580. PhysicsEngine.prototype._setGravity = function (gravity) {
  16581. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  16582. this._currentPlugin.setGravity(this.gravity);
  16583. };
  16584. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  16585. return this._currentPlugin.registerMesh(mesh, impostor, options);
  16586. };
  16587. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  16588. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  16589. };
  16590. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  16591. this._currentPlugin.unregisterMesh(mesh);
  16592. };
  16593. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  16594. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  16595. };
  16596. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16597. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  16598. };
  16599. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  16600. this._currentPlugin.updateBodyPosition(mesh);
  16601. };
  16602. PhysicsEngine.prototype.dispose = function () {
  16603. this._currentPlugin.dispose();
  16604. };
  16605. PhysicsEngine.prototype.isSupported = function () {
  16606. return this._currentPlugin.isSupported();
  16607. };
  16608. PhysicsEngine.NoImpostor = 0;
  16609. PhysicsEngine.SphereImpostor = 1;
  16610. PhysicsEngine.BoxImpostor = 2;
  16611. PhysicsEngine.PlaneImpostor = 3;
  16612. PhysicsEngine.MeshImpostor = 4;
  16613. PhysicsEngine.CapsuleImpostor = 5;
  16614. PhysicsEngine.ConeImpostor = 6;
  16615. PhysicsEngine.CylinderImpostor = 7;
  16616. PhysicsEngine.ConvexHullImpostor = 8;
  16617. PhysicsEngine.Epsilon = 0.001;
  16618. return PhysicsEngine;
  16619. })();
  16620. BABYLON.PhysicsEngine = PhysicsEngine;
  16621. })(BABYLON || (BABYLON = {}));
  16622. //# sourceMappingURL=babylon.physicsEngine.js.map
  16623. var BABYLON;
  16624. (function (BABYLON) {
  16625. var serializeLight = function (light) {
  16626. var serializationObject = {};
  16627. serializationObject.name = light.name;
  16628. serializationObject.id = light.id;
  16629. serializationObject.tags = BABYLON.Tags.GetTags(light);
  16630. if (light instanceof BABYLON.PointLight) {
  16631. serializationObject.type = 0;
  16632. serializationObject.position = light.position.asArray();
  16633. } else if (light instanceof BABYLON.DirectionalLight) {
  16634. serializationObject.type = 1;
  16635. var directionalLight = light;
  16636. serializationObject.position = directionalLight.position.asArray();
  16637. serializationObject.direction = directionalLight.direction.asArray();
  16638. } else if (light instanceof BABYLON.SpotLight) {
  16639. serializationObject.type = 2;
  16640. var spotLight = light;
  16641. serializationObject.position = spotLight.position.asArray();
  16642. serializationObject.direction = spotLight.position.asArray();
  16643. serializationObject.angle = spotLight.angle;
  16644. serializationObject.exponent = spotLight.exponent;
  16645. } else if (light instanceof BABYLON.HemisphericLight) {
  16646. serializationObject.type = 3;
  16647. var hemisphericLight = light;
  16648. serializationObject.direction = hemisphericLight.direction.asArray();
  16649. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  16650. }
  16651. if (light.intensity) {
  16652. serializationObject.intensity = light.intensity;
  16653. }
  16654. serializationObject.range = light.range;
  16655. serializationObject.diffuse = light.diffuse.asArray();
  16656. serializationObject.specular = light.specular.asArray();
  16657. return serializationObject;
  16658. };
  16659. var serializeFresnelParameter = function (fresnelParameter) {
  16660. var serializationObject = {};
  16661. serializationObject.isEnabled = fresnelParameter.isEnabled;
  16662. serializationObject.leftColor = fresnelParameter.leftColor;
  16663. serializationObject.rightColor = fresnelParameter.rightColor;
  16664. serializationObject.bias = fresnelParameter.bias;
  16665. serializationObject.power = fresnelParameter.power;
  16666. return serializationObject;
  16667. };
  16668. var serializeCamera = function (camera) {
  16669. var serializationObject = {};
  16670. serializationObject.name = camera.name;
  16671. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  16672. serializationObject.id = camera.id;
  16673. serializationObject.position = camera.position.asArray();
  16674. // Parent
  16675. if (camera.parent) {
  16676. serializationObject.parentId = camera.parent.id;
  16677. }
  16678. // Target
  16679. serializationObject.rotation = camera.rotation.asArray();
  16680. // Locked target
  16681. if (camera.lockedTarget && camera.lockedTarget.id) {
  16682. serializationObject.lockedTargetId = camera.lockedTarget.id;
  16683. }
  16684. serializationObject.fov = camera.fov;
  16685. serializationObject.minZ = camera.minZ;
  16686. serializationObject.maxZ = camera.maxZ;
  16687. serializationObject.speed = camera.speed;
  16688. serializationObject.inertia = camera.inertia;
  16689. serializationObject.checkCollisions = camera.checkCollisions;
  16690. serializationObject.applyGravity = camera.applyGravity;
  16691. if (camera.ellipsoid) {
  16692. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  16693. }
  16694. // Animations
  16695. appendAnimations(camera, serializationObject);
  16696. // Layer mask
  16697. serializationObject.layerMask = camera.layerMask;
  16698. return serializationObject;
  16699. };
  16700. var appendAnimations = function (source, destination) {
  16701. if (source.animations) {
  16702. destination.animations = [];
  16703. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  16704. var animation = source.animations[animationIndex];
  16705. destination.animations.push(serializeAnimation(animation));
  16706. }
  16707. }
  16708. };
  16709. var serializeAnimation = function (animation) {
  16710. var serializationObject = {};
  16711. serializationObject.name = animation.name;
  16712. serializationObject.property = animation.targetProperty;
  16713. serializationObject.framePerSecond = animation.framePerSecond;
  16714. serializationObject.dataType = animation.dataType;
  16715. serializationObject.loopBehavior = animation.loopMode;
  16716. var dataType = animation.dataType;
  16717. serializationObject.keys = [];
  16718. var keys = animation.getKeys();
  16719. for (var index = 0; index < keys.length; index++) {
  16720. var animationKey = keys[index];
  16721. var key = {};
  16722. key.frame = animationKey.frame;
  16723. switch (dataType) {
  16724. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16725. key.values = [animationKey.value];
  16726. break;
  16727. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16728. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16729. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16730. key.values = animationKey.value.asArray();
  16731. break;
  16732. }
  16733. serializationObject.keys.push(key);
  16734. }
  16735. return serializationObject;
  16736. };
  16737. var serializeMultiMaterial = function (material) {
  16738. var serializationObject = {};
  16739. serializationObject.name = material.name;
  16740. serializationObject.id = material.id;
  16741. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16742. serializationObject.materials = [];
  16743. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  16744. var subMat = material.subMaterials[matIndex];
  16745. if (subMat) {
  16746. serializationObject.materials.push(subMat.id);
  16747. } else {
  16748. serializationObject.materials.push(null);
  16749. }
  16750. }
  16751. return serializationObject;
  16752. };
  16753. var serializeMaterial = function (material) {
  16754. var serializationObject = {};
  16755. serializationObject.name = material.name;
  16756. serializationObject.ambient = material.ambientColor.asArray();
  16757. serializationObject.diffuse = material.diffuseColor.asArray();
  16758. serializationObject.specular = material.specularColor.asArray();
  16759. serializationObject.specularPower = material.specularPower;
  16760. serializationObject.emissive = material.emissiveColor.asArray();
  16761. serializationObject.alpha = material.alpha;
  16762. serializationObject.id = material.id;
  16763. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16764. serializationObject.backFaceCulling = material.backFaceCulling;
  16765. if (material.diffuseTexture) {
  16766. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  16767. }
  16768. if (material.diffuseFresnelParameters) {
  16769. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  16770. }
  16771. if (material.ambientTexture) {
  16772. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  16773. }
  16774. if (material.opacityTexture) {
  16775. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  16776. }
  16777. if (material.opacityFresnelParameters) {
  16778. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  16779. }
  16780. if (material.reflectionTexture) {
  16781. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  16782. }
  16783. if (material.reflectionFresnelParameters) {
  16784. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  16785. }
  16786. if (material.emissiveTexture) {
  16787. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  16788. }
  16789. if (material.emissiveFresnelParameters) {
  16790. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  16791. }
  16792. if (material.specularTexture) {
  16793. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  16794. }
  16795. if (material.bumpTexture) {
  16796. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  16797. }
  16798. return serializationObject;
  16799. };
  16800. var serializeTexture = function (texture) {
  16801. var serializationObject = {};
  16802. if (!texture.name) {
  16803. return null;
  16804. }
  16805. if (texture instanceof BABYLON.CubeTexture) {
  16806. serializationObject.name = texture.name;
  16807. serializationObject.hasAlpha = texture.hasAlpha;
  16808. serializationObject.level = texture.level;
  16809. serializationObject.coordinatesMode = texture.coordinatesMode;
  16810. return serializationObject;
  16811. }
  16812. if (texture instanceof BABYLON.MirrorTexture) {
  16813. var mirrorTexture = texture;
  16814. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  16815. serializationObject.renderList = [];
  16816. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  16817. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  16818. }
  16819. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  16820. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  16821. var renderTargetTexture = texture;
  16822. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  16823. serializationObject.renderList = [];
  16824. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  16825. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  16826. }
  16827. }
  16828. var regularTexture = texture;
  16829. serializationObject.name = texture.name;
  16830. serializationObject.hasAlpha = texture.hasAlpha;
  16831. serializationObject.level = texture.level;
  16832. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  16833. serializationObject.coordinatesMode = texture.coordinatesMode;
  16834. serializationObject.uOffset = regularTexture.uOffset;
  16835. serializationObject.vOffset = regularTexture.vOffset;
  16836. serializationObject.uScale = regularTexture.uScale;
  16837. serializationObject.vScale = regularTexture.vScale;
  16838. serializationObject.uAng = regularTexture.uAng;
  16839. serializationObject.vAng = regularTexture.vAng;
  16840. serializationObject.wAng = regularTexture.wAng;
  16841. serializationObject.wrapU = texture.wrapU;
  16842. serializationObject.wrapV = texture.wrapV;
  16843. // Animations
  16844. appendAnimations(texture, serializationObject);
  16845. return serializationObject;
  16846. };
  16847. var serializeSkeleton = function (skeleton) {
  16848. var serializationObject = {};
  16849. serializationObject.name = skeleton.name;
  16850. serializationObject.id = skeleton.id;
  16851. serializationObject.bones = [];
  16852. for (var index = 0; index < skeleton.bones.length; index++) {
  16853. var bone = skeleton.bones[index];
  16854. var serializedBone = {
  16855. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  16856. name: bone.name,
  16857. matrix: bone.getLocalMatrix().toArray()
  16858. };
  16859. serializationObject.bones.push(serializedBone);
  16860. if (bone.animations && bone.animations.length > 0) {
  16861. serializedBone.animation = serializeAnimation(bone.animations[0]);
  16862. }
  16863. }
  16864. return serializationObject;
  16865. };
  16866. var serializeParticleSystem = function (particleSystem) {
  16867. var serializationObject = {};
  16868. serializationObject.emitterId = particleSystem.emitter.id;
  16869. serializationObject.capacity = particleSystem.getCapacity();
  16870. if (particleSystem.particleTexture) {
  16871. serializationObject.textureName = particleSystem.particleTexture.name;
  16872. }
  16873. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  16874. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  16875. serializationObject.minSize = particleSystem.minSize;
  16876. serializationObject.maxSize = particleSystem.maxSize;
  16877. serializationObject.minLifeTime = particleSystem.minLifeTime;
  16878. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  16879. serializationObject.emitRate = particleSystem.emitRate;
  16880. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  16881. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  16882. serializationObject.gravity = particleSystem.gravity.asArray();
  16883. serializationObject.direction1 = particleSystem.direction1.asArray();
  16884. serializationObject.direction2 = particleSystem.direction2.asArray();
  16885. serializationObject.color1 = particleSystem.color1.asArray();
  16886. serializationObject.color2 = particleSystem.color2.asArray();
  16887. serializationObject.colorDead = particleSystem.colorDead.asArray();
  16888. serializationObject.updateSpeed = particleSystem.updateSpeed;
  16889. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  16890. serializationObject.textureMask = particleSystem.textureMask.asArray();
  16891. serializationObject.blendMode = particleSystem.blendMode;
  16892. return serializationObject;
  16893. };
  16894. var serializeLensFlareSystem = function (lensFlareSystem) {
  16895. var serializationObject = {};
  16896. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  16897. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  16898. serializationObject.flares = [];
  16899. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  16900. var flare = lensFlareSystem.lensFlares[index];
  16901. serializationObject.flares.push({
  16902. size: flare.size,
  16903. position: flare.position,
  16904. color: flare.color.asArray(),
  16905. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  16906. });
  16907. }
  16908. return serializationObject;
  16909. };
  16910. var serializeShadowGenerator = function (light) {
  16911. var serializationObject = {};
  16912. var shadowGenerator = light.getShadowGenerator();
  16913. serializationObject.lightId = light.id;
  16914. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  16915. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  16916. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  16917. serializationObject.renderList = [];
  16918. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  16919. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  16920. serializationObject.renderList.push(mesh.id);
  16921. }
  16922. return serializationObject;
  16923. };
  16924. var serializedGeometries = [];
  16925. var serializeGeometry = function (geometry, serializationGeometries) {
  16926. if (serializedGeometries[geometry.id]) {
  16927. return;
  16928. }
  16929. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  16930. serializationGeometries.boxes.push(serializeBox(geometry));
  16931. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  16932. serializationGeometries.spheres.push(serializeSphere(geometry));
  16933. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  16934. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  16935. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  16936. serializationGeometries.toruses.push(serializeTorus(geometry));
  16937. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  16938. serializationGeometries.grounds.push(serializeGround(geometry));
  16939. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  16940. serializationGeometries.planes.push(serializePlane(geometry));
  16941. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  16942. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  16943. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  16944. throw new Error("Unknow primitive type");
  16945. } else {
  16946. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  16947. }
  16948. serializedGeometries[geometry.id] = true;
  16949. };
  16950. var serializeGeometryBase = function (geometry) {
  16951. var serializationObject = {};
  16952. serializationObject.id = geometry.id;
  16953. if (BABYLON.Tags.HasTags(geometry)) {
  16954. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  16955. }
  16956. return serializationObject;
  16957. };
  16958. var serializeVertexData = function (vertexData) {
  16959. var serializationObject = serializeGeometryBase(vertexData);
  16960. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16961. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16962. }
  16963. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16964. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16965. }
  16966. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16967. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16968. }
  16969. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16970. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16971. }
  16972. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16973. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16974. }
  16975. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16976. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16977. serializationObject.matricesIndices._isExpanded = true;
  16978. }
  16979. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16980. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16981. }
  16982. serializationObject.indices = vertexData.getIndices();
  16983. return serializationObject;
  16984. };
  16985. var serializePrimitive = function (primitive) {
  16986. var serializationObject = serializeGeometryBase(primitive);
  16987. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  16988. return serializationObject;
  16989. };
  16990. var serializeBox = function (box) {
  16991. var serializationObject = serializePrimitive(box);
  16992. serializationObject.size = box.size;
  16993. return serializationObject;
  16994. };
  16995. var serializeSphere = function (sphere) {
  16996. var serializationObject = serializePrimitive(sphere);
  16997. serializationObject.segments = sphere.segments;
  16998. serializationObject.diameter = sphere.diameter;
  16999. return serializationObject;
  17000. };
  17001. var serializeCylinder = function (cylinder) {
  17002. var serializationObject = serializePrimitive(cylinder);
  17003. serializationObject.height = cylinder.height;
  17004. serializationObject.diameterTop = cylinder.diameterTop;
  17005. serializationObject.diameterBottom = cylinder.diameterBottom;
  17006. serializationObject.tessellation = cylinder.tessellation;
  17007. return serializationObject;
  17008. };
  17009. var serializeTorus = function (torus) {
  17010. var serializationObject = serializePrimitive(torus);
  17011. serializationObject.diameter = torus.diameter;
  17012. serializationObject.thickness = torus.thickness;
  17013. serializationObject.tessellation = torus.tessellation;
  17014. return serializationObject;
  17015. };
  17016. var serializeGround = function (ground) {
  17017. var serializationObject = serializePrimitive(ground);
  17018. serializationObject.width = ground.width;
  17019. serializationObject.height = ground.height;
  17020. serializationObject.subdivisions = ground.subdivisions;
  17021. return serializationObject;
  17022. };
  17023. var serializePlane = function (plane) {
  17024. var serializationObject = serializePrimitive(plane);
  17025. serializationObject.size = plane.size;
  17026. return serializationObject;
  17027. };
  17028. var serializeTorusKnot = function (torusKnot) {
  17029. var serializationObject = serializePrimitive(torusKnot);
  17030. serializationObject.radius = torusKnot.radius;
  17031. serializationObject.tube = torusKnot.tube;
  17032. serializationObject.radialSegments = torusKnot.radialSegments;
  17033. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17034. serializationObject.p = torusKnot.p;
  17035. serializationObject.q = torusKnot.q;
  17036. return serializationObject;
  17037. };
  17038. var serializeMesh = function (mesh, serializationScene) {
  17039. var serializationObject = {};
  17040. serializationObject.name = mesh.name;
  17041. serializationObject.id = mesh.id;
  17042. if (BABYLON.Tags.HasTags(mesh)) {
  17043. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17044. }
  17045. serializationObject.position = mesh.position.asArray();
  17046. if (mesh.rotationQuaternion) {
  17047. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17048. } else if (mesh.rotation) {
  17049. serializationObject.rotation = mesh.rotation.asArray();
  17050. }
  17051. serializationObject.scaling = mesh.scaling.asArray();
  17052. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17053. serializationObject.isEnabled = mesh.isEnabled();
  17054. serializationObject.isVisible = mesh.isVisible;
  17055. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17056. serializationObject.pickable = mesh.isPickable;
  17057. serializationObject.receiveShadows = mesh.receiveShadows;
  17058. serializationObject.billboardMode = mesh.billboardMode;
  17059. serializationObject.visibility = mesh.visibility;
  17060. serializationObject.checkCollisions = mesh.checkCollisions;
  17061. // Parent
  17062. if (mesh.parent) {
  17063. serializationObject.parentId = mesh.parent.id;
  17064. }
  17065. // Geometry
  17066. var geometry = mesh._geometry;
  17067. if (geometry) {
  17068. var geometryId = geometry.id;
  17069. serializationObject.geometryId = geometryId;
  17070. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17071. // 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
  17072. serializeGeometry(geometry, serializationScene.geometries);
  17073. }
  17074. // SubMeshes
  17075. serializationObject.subMeshes = [];
  17076. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17077. var subMesh = mesh.subMeshes[subIndex];
  17078. serializationObject.subMeshes.push({
  17079. materialIndex: subMesh.materialIndex,
  17080. verticesStart: subMesh.verticesStart,
  17081. verticesCount: subMesh.verticesCount,
  17082. indexStart: subMesh.indexStart,
  17083. indexCount: subMesh.indexCount
  17084. });
  17085. }
  17086. }
  17087. // Material
  17088. if (mesh.material) {
  17089. serializationObject.materialId = mesh.material.id;
  17090. } else {
  17091. mesh.material = null;
  17092. }
  17093. // Skeleton
  17094. if (mesh.skeleton) {
  17095. serializationObject.skeletonId = mesh.skeleton.id;
  17096. }
  17097. // Physics
  17098. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17099. serializationObject.physicsMass = mesh.getPhysicsMass();
  17100. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17101. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17102. switch (mesh.getPhysicsImpostor()) {
  17103. case BABYLON.PhysicsEngine.BoxImpostor:
  17104. serializationObject.physicsImpostor = 1;
  17105. break;
  17106. case BABYLON.PhysicsEngine.SphereImpostor:
  17107. serializationObject.physicsImpostor = 2;
  17108. break;
  17109. }
  17110. }
  17111. // Instances
  17112. serializationObject.instances = [];
  17113. for (var index = 0; index < mesh.instances.length; index++) {
  17114. var instance = mesh.instances[index];
  17115. var serializationInstance = {
  17116. name: instance.name,
  17117. position: instance.position,
  17118. rotation: instance.rotation,
  17119. rotationQuaternion: instance.rotationQuaternion,
  17120. scaling: instance.scaling
  17121. };
  17122. serializationObject.instances.push(serializationInstance);
  17123. // Animations
  17124. appendAnimations(instance, serializationInstance);
  17125. }
  17126. // Animations
  17127. appendAnimations(mesh, serializationObject);
  17128. // Layer mask
  17129. serializationObject.layerMask = mesh.layerMask;
  17130. return serializationObject;
  17131. };
  17132. var SceneSerializer = (function () {
  17133. function SceneSerializer() {
  17134. }
  17135. SceneSerializer.Serialize = function (scene) {
  17136. var serializationObject = {};
  17137. // Scene
  17138. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17139. serializationObject.autoClear = scene.autoClear;
  17140. serializationObject.clearColor = scene.clearColor.asArray();
  17141. serializationObject.ambientColor = scene.ambientColor.asArray();
  17142. serializationObject.gravity = scene.gravity.asArray();
  17143. // Fog
  17144. if (scene.fogMode && scene.fogMode !== 0) {
  17145. serializationObject.fogMode = scene.fogMode;
  17146. serializationObject.fogColor = scene.fogColor.asArray();
  17147. serializationObject.fogStart = scene.fogStart;
  17148. serializationObject.fogEnd = scene.fogEnd;
  17149. serializationObject.fogDensity = scene.fogDensity;
  17150. }
  17151. // Lights
  17152. serializationObject.lights = [];
  17153. for (var index = 0; index < scene.lights.length; index++) {
  17154. var light = scene.lights[index];
  17155. serializationObject.lights.push(serializeLight(light));
  17156. }
  17157. // Cameras
  17158. serializationObject.cameras = [];
  17159. for (index = 0; index < scene.cameras.length; index++) {
  17160. var camera = scene.cameras[index];
  17161. if (camera instanceof BABYLON.FreeCamera) {
  17162. serializationObject.cameras.push(serializeCamera(camera));
  17163. }
  17164. }
  17165. if (scene.activeCamera) {
  17166. serializationObject.activeCameraID = scene.activeCamera.id;
  17167. }
  17168. // Materials
  17169. serializationObject.materials = [];
  17170. serializationObject.multiMaterials = [];
  17171. for (index = 0; index < scene.materials.length; index++) {
  17172. var material = scene.materials[index];
  17173. if (material instanceof BABYLON.StandardMaterial) {
  17174. serializationObject.materials.push(serializeMaterial(material));
  17175. } else if (material instanceof BABYLON.MultiMaterial) {
  17176. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17177. }
  17178. }
  17179. // Skeletons
  17180. serializationObject.skeletons = [];
  17181. for (index = 0; index < scene.skeletons.length; index++) {
  17182. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17183. }
  17184. // Geometries
  17185. serializationObject.geometries = {};
  17186. serializationObject.geometries.boxes = [];
  17187. serializationObject.geometries.spheres = [];
  17188. serializationObject.geometries.cylinders = [];
  17189. serializationObject.geometries.toruses = [];
  17190. serializationObject.geometries.grounds = [];
  17191. serializationObject.geometries.planes = [];
  17192. serializationObject.geometries.torusKnots = [];
  17193. serializationObject.geometries.vertexData = [];
  17194. serializedGeometries = [];
  17195. var geometries = scene.getGeometries();
  17196. for (var index = 0; index < geometries.length; index++) {
  17197. var geometry = geometries[index];
  17198. if (geometry.isReady()) {
  17199. serializeGeometry(geometry, serializationObject.geometries);
  17200. }
  17201. }
  17202. // Meshes
  17203. serializationObject.meshes = [];
  17204. for (index = 0; index < scene.meshes.length; index++) {
  17205. var abstractMesh = scene.meshes[index];
  17206. if (abstractMesh instanceof BABYLON.Mesh) {
  17207. var mesh = abstractMesh;
  17208. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  17209. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  17210. }
  17211. }
  17212. }
  17213. // Particles Systems
  17214. serializationObject.particleSystems = [];
  17215. for (index = 0; index < scene.particleSystems.length; index++) {
  17216. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  17217. }
  17218. // Lens flares
  17219. serializationObject.lensFlareSystems = [];
  17220. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  17221. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  17222. }
  17223. // Shadows
  17224. serializationObject.shadowGenerators = [];
  17225. for (index = 0; index < scene.lights.length; index++) {
  17226. light = scene.lights[index];
  17227. if (light.getShadowGenerator()) {
  17228. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  17229. }
  17230. }
  17231. return serializationObject;
  17232. };
  17233. return SceneSerializer;
  17234. })();
  17235. BABYLON.SceneSerializer = SceneSerializer;
  17236. })(BABYLON || (BABYLON = {}));
  17237. //# sourceMappingURL=babylon.sceneSerializer.js.map
  17238. var BABYLON;
  17239. (function (BABYLON) {
  17240. var SceneLoader = (function () {
  17241. function SceneLoader() {
  17242. }
  17243. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17244. get: function () {
  17245. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17246. },
  17247. set: function (value) {
  17248. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17249. },
  17250. enumerable: true,
  17251. configurable: true
  17252. });
  17253. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17254. get: function () {
  17255. return SceneLoader._ShowLoadingScreen;
  17256. },
  17257. set: function (value) {
  17258. SceneLoader._ShowLoadingScreen = value;
  17259. },
  17260. enumerable: true,
  17261. configurable: true
  17262. });
  17263. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17264. var dotPosition = sceneFilename.lastIndexOf(".");
  17265. var queryStringPosition = sceneFilename.indexOf("?");
  17266. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17267. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17268. var plugin = this._registeredPlugins[index];
  17269. if (plugin.extensions.indexOf(extension) !== -1) {
  17270. return plugin;
  17271. }
  17272. }
  17273. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17274. };
  17275. // Public functions
  17276. SceneLoader.RegisterPlugin = function (plugin) {
  17277. plugin.extensions = plugin.extensions.toLowerCase();
  17278. SceneLoader._registeredPlugins.push(plugin);
  17279. };
  17280. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17281. var manifestChecked = function (success) {
  17282. scene.database = database;
  17283. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17284. var importMeshFromData = function (data) {
  17285. var meshes = [];
  17286. var particleSystems = [];
  17287. var skeletons = [];
  17288. try {
  17289. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17290. if (onerror) {
  17291. onerror(scene, 'unable to load the scene');
  17292. }
  17293. return;
  17294. }
  17295. } catch (e) {
  17296. if (onerror) {
  17297. onerror(scene, e);
  17298. }
  17299. return;
  17300. }
  17301. if (onsuccess) {
  17302. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17303. onsuccess(meshes, particleSystems, skeletons);
  17304. }
  17305. };
  17306. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17307. // Direct load
  17308. importMeshFromData(sceneFilename.substr(5));
  17309. return;
  17310. }
  17311. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17312. importMeshFromData(data);
  17313. }, progressCallBack, database);
  17314. };
  17315. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17316. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17317. };
  17318. /**
  17319. * Load a scene
  17320. * @param rootUrl a string that defines the root url for scene and resources
  17321. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17322. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17323. */
  17324. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17325. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17326. };
  17327. /**
  17328. * Append a scene
  17329. * @param rootUrl a string that defines the root url for scene and resources
  17330. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17331. * @param scene is the instance of BABYLON.Scene to append to
  17332. */
  17333. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17334. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17335. var database;
  17336. if (SceneLoader.ShowLoadingScreen) {
  17337. scene.getEngine().displayLoadingUI();
  17338. }
  17339. var loadSceneFromData = function (data) {
  17340. scene.database = database;
  17341. if (!plugin.load(scene, data, rootUrl)) {
  17342. if (onerror) {
  17343. onerror(scene);
  17344. }
  17345. scene.getEngine().hideLoadingUI();
  17346. return;
  17347. }
  17348. if (onsuccess) {
  17349. onsuccess(scene);
  17350. }
  17351. if (SceneLoader.ShowLoadingScreen) {
  17352. scene.executeWhenReady(function () {
  17353. scene.getEngine().hideLoadingUI();
  17354. });
  17355. }
  17356. };
  17357. var manifestChecked = function (success) {
  17358. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17359. };
  17360. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17361. // Direct load
  17362. loadSceneFromData(sceneFilename.substr(5));
  17363. return;
  17364. }
  17365. if (rootUrl.indexOf("file:") === -1) {
  17366. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17367. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17368. } else {
  17369. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17370. }
  17371. };
  17372. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17373. SceneLoader._ShowLoadingScreen = true;
  17374. SceneLoader._registeredPlugins = new Array();
  17375. return SceneLoader;
  17376. })();
  17377. BABYLON.SceneLoader = SceneLoader;
  17378. ;
  17379. })(BABYLON || (BABYLON = {}));
  17380. //# sourceMappingURL=babylon.sceneLoader.js.map
  17381. var BABYLON;
  17382. (function (BABYLON) {
  17383. (function (Internals) {
  17384. var checkColors4 = function (colors, count) {
  17385. // Check if color3 was used
  17386. if (colors.length === count * 3) {
  17387. var colors4 = [];
  17388. for (var index = 0; index < colors.length; index += 3) {
  17389. var newIndex = (index / 3) * 4;
  17390. colors4[newIndex] = colors[index];
  17391. colors4[newIndex + 1] = colors[index + 1];
  17392. colors4[newIndex + 2] = colors[index + 2];
  17393. colors4[newIndex + 3] = 1.0;
  17394. }
  17395. return colors4;
  17396. }
  17397. return colors;
  17398. };
  17399. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17400. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17401. texture.name = parsedTexture.name;
  17402. texture.hasAlpha = parsedTexture.hasAlpha;
  17403. texture.level = parsedTexture.level;
  17404. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17405. return texture;
  17406. };
  17407. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17408. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17409. return null;
  17410. }
  17411. if (parsedTexture.isCube) {
  17412. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17413. }
  17414. var texture;
  17415. if (parsedTexture.mirrorPlane) {
  17416. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17417. texture._waitingRenderList = parsedTexture.renderList;
  17418. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17419. } else if (parsedTexture.isRenderTarget) {
  17420. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17421. texture._waitingRenderList = parsedTexture.renderList;
  17422. } else {
  17423. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17424. }
  17425. texture.name = parsedTexture.name;
  17426. texture.hasAlpha = parsedTexture.hasAlpha;
  17427. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17428. texture.level = parsedTexture.level;
  17429. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17430. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17431. texture.uOffset = parsedTexture.uOffset;
  17432. texture.vOffset = parsedTexture.vOffset;
  17433. texture.uScale = parsedTexture.uScale;
  17434. texture.vScale = parsedTexture.vScale;
  17435. texture.uAng = parsedTexture.uAng;
  17436. texture.vAng = parsedTexture.vAng;
  17437. texture.wAng = parsedTexture.wAng;
  17438. texture.wrapU = parsedTexture.wrapU;
  17439. texture.wrapV = parsedTexture.wrapV;
  17440. // Animations
  17441. if (parsedTexture.animations) {
  17442. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17443. var parsedAnimation = parsedTexture.animations[animationIndex];
  17444. texture.animations.push(parseAnimation(parsedAnimation));
  17445. }
  17446. }
  17447. return texture;
  17448. };
  17449. var parseSkeleton = function (parsedSkeleton, scene) {
  17450. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17451. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17452. var parsedBone = parsedSkeleton.bones[index];
  17453. var parentBone = null;
  17454. if (parsedBone.parentBoneIndex > -1) {
  17455. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17456. }
  17457. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17458. if (parsedBone.animation) {
  17459. bone.animations.push(parseAnimation(parsedBone.animation));
  17460. }
  17461. }
  17462. return skeleton;
  17463. };
  17464. var parseFresnelParameters = function (parsedFresnelParameters) {
  17465. var fresnelParameters = new BABYLON.FresnelParameters();
  17466. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17467. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17468. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17469. fresnelParameters.bias = parsedFresnelParameters.bias;
  17470. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17471. return fresnelParameters;
  17472. };
  17473. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17474. var material;
  17475. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17476. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17477. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17478. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17479. material.specularPower = parsedMaterial.specularPower;
  17480. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17481. material.alpha = parsedMaterial.alpha;
  17482. material.id = parsedMaterial.id;
  17483. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17484. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17485. material.wireframe = parsedMaterial.wireframe;
  17486. if (parsedMaterial.diffuseTexture) {
  17487. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17488. }
  17489. if (parsedMaterial.diffuseFresnelParameters) {
  17490. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17491. }
  17492. if (parsedMaterial.ambientTexture) {
  17493. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17494. }
  17495. if (parsedMaterial.opacityTexture) {
  17496. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17497. }
  17498. if (parsedMaterial.opacityFresnelParameters) {
  17499. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17500. }
  17501. if (parsedMaterial.reflectionTexture) {
  17502. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17503. }
  17504. if (parsedMaterial.reflectionFresnelParameters) {
  17505. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17506. }
  17507. if (parsedMaterial.emissiveTexture) {
  17508. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17509. }
  17510. if (parsedMaterial.emissiveFresnelParameters) {
  17511. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17512. }
  17513. if (parsedMaterial.specularTexture) {
  17514. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17515. }
  17516. if (parsedMaterial.bumpTexture) {
  17517. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17518. }
  17519. return material;
  17520. };
  17521. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17522. for (var index = 0; index < parsedData.materials.length; index++) {
  17523. var parsedMaterial = parsedData.materials[index];
  17524. if (parsedMaterial.id === id) {
  17525. return parseMaterial(parsedMaterial, scene, rootUrl);
  17526. }
  17527. }
  17528. return null;
  17529. };
  17530. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17531. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17532. multiMaterial.id = parsedMultiMaterial.id;
  17533. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17534. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17535. var subMatId = parsedMultiMaterial.materials[matIndex];
  17536. if (subMatId) {
  17537. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17538. } else {
  17539. multiMaterial.subMaterials.push(null);
  17540. }
  17541. }
  17542. return multiMaterial;
  17543. };
  17544. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17545. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17546. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17547. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17548. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17549. var parsedFlare = parsedLensFlareSystem.flares[index];
  17550. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17551. }
  17552. return lensFlareSystem;
  17553. };
  17554. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17555. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17556. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17557. if (parsedParticleSystem.textureName) {
  17558. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17559. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17560. }
  17561. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17562. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17563. particleSystem.minSize = parsedParticleSystem.minSize;
  17564. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17565. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17566. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17567. particleSystem.emitter = emitter;
  17568. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17569. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17570. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17571. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17572. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17573. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17574. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17575. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17576. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17577. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17578. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17579. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17580. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17581. particleSystem.start();
  17582. return particleSystem;
  17583. };
  17584. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17585. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17586. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17587. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17588. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17589. shadowGenerator.getShadowMap().renderList.push(mesh);
  17590. }
  17591. if (parsedShadowGenerator.usePoissonSampling) {
  17592. shadowGenerator.usePoissonSampling = true;
  17593. } else {
  17594. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  17595. }
  17596. return shadowGenerator;
  17597. };
  17598. var parseAnimation = function (parsedAnimation) {
  17599. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17600. var dataType = parsedAnimation.dataType;
  17601. var keys = [];
  17602. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17603. var key = parsedAnimation.keys[index];
  17604. var data;
  17605. switch (dataType) {
  17606. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17607. data = key.values[0];
  17608. break;
  17609. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17610. data = BABYLON.Quaternion.FromArray(key.values);
  17611. break;
  17612. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17613. data = BABYLON.Matrix.FromArray(key.values);
  17614. break;
  17615. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17616. default:
  17617. data = BABYLON.Vector3.FromArray(key.values);
  17618. break;
  17619. }
  17620. keys.push({
  17621. frame: key.frame,
  17622. value: data
  17623. });
  17624. }
  17625. animation.setKeys(keys);
  17626. return animation;
  17627. };
  17628. var parseLight = function (parsedLight, scene) {
  17629. var light;
  17630. switch (parsedLight.type) {
  17631. case 0:
  17632. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17633. break;
  17634. case 1:
  17635. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17636. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17637. break;
  17638. case 2:
  17639. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17640. break;
  17641. case 3:
  17642. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17643. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17644. break;
  17645. }
  17646. light.id = parsedLight.id;
  17647. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17648. if (parsedLight.intensity !== undefined) {
  17649. light.intensity = parsedLight.intensity;
  17650. }
  17651. if (parsedLight.range) {
  17652. light.range = parsedLight.range;
  17653. }
  17654. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17655. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17656. if (parsedLight.excludedMeshesIds) {
  17657. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17658. }
  17659. // Parent
  17660. if (parsedLight.parentId) {
  17661. light._waitingParentId = parsedLight.parentId;
  17662. }
  17663. if (parsedLight.includedOnlyMeshesIds) {
  17664. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17665. }
  17666. // Actions
  17667. if (parsedLight.actions !== undefined) {
  17668. light._waitingActions = parsedLight.actions;
  17669. }
  17670. // Animations
  17671. if (parsedLight.animations) {
  17672. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17673. var parsedAnimation = parsedLight.animations[animationIndex];
  17674. light.animations.push(parseAnimation(parsedAnimation));
  17675. }
  17676. }
  17677. if (parsedLight.autoAnimate) {
  17678. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17679. }
  17680. };
  17681. var parseCamera = function (parsedCamera, scene) {
  17682. var camera;
  17683. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17684. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17685. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17686. var alpha = parsedCamera.alpha;
  17687. var beta = parsedCamera.beta;
  17688. var radius = parsedCamera.radius;
  17689. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17690. var eye_space = parsedCamera.eye_space;
  17691. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17692. } else {
  17693. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17694. }
  17695. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17696. eye_space = parsedCamera.eye_space;
  17697. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17698. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  17699. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17700. } else if (parsedCamera.type === "FollowCamera") {
  17701. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17702. camera.heightOffset = parsedCamera.heightOffset;
  17703. camera.radius = parsedCamera.radius;
  17704. camera.rotationOffset = parsedCamera.rotationOffset;
  17705. if (lockedTargetMesh)
  17706. camera.target = lockedTargetMesh;
  17707. } else if (parsedCamera.type === "GamepadCamera") {
  17708. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17709. } else if (parsedCamera.type === "OculusCamera") {
  17710. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17711. } else if (parsedCamera.type === "OculusGamepadCamera") {
  17712. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17713. } else if (parsedCamera.type === "TouchCamera") {
  17714. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17715. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17716. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17717. } else if (parsedCamera.type === "WebVRCamera") {
  17718. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17719. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17720. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17721. } else {
  17722. // Free Camera is the default value
  17723. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17724. }
  17725. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17726. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17727. camera.lockedTarget = lockedTargetMesh;
  17728. }
  17729. camera.id = parsedCamera.id;
  17730. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17731. // Parent
  17732. if (parsedCamera.parentId) {
  17733. camera._waitingParentId = parsedCamera.parentId;
  17734. }
  17735. // Actions
  17736. if (parsedCamera.actions !== undefined) {
  17737. camera._waitingActions = parsedCamera.actions;
  17738. }
  17739. // Target
  17740. if (parsedCamera.target) {
  17741. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17742. } else {
  17743. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17744. }
  17745. camera.fov = parsedCamera.fov;
  17746. camera.minZ = parsedCamera.minZ;
  17747. camera.maxZ = parsedCamera.maxZ;
  17748. camera.speed = parsedCamera.speed;
  17749. camera.inertia = parsedCamera.inertia;
  17750. camera.checkCollisions = parsedCamera.checkCollisions;
  17751. camera.applyGravity = parsedCamera.applyGravity;
  17752. if (parsedCamera.ellipsoid) {
  17753. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17754. }
  17755. // Animations
  17756. if (parsedCamera.animations) {
  17757. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17758. var parsedAnimation = parsedCamera.animations[animationIndex];
  17759. camera.animations.push(parseAnimation(parsedAnimation));
  17760. }
  17761. }
  17762. if (parsedCamera.autoAnimate) {
  17763. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17764. }
  17765. // Layer Mask
  17766. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17767. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17768. } else {
  17769. camera.layerMask = 0xFFFFFFFF;
  17770. }
  17771. return camera;
  17772. };
  17773. var parseGeometry = function (parsedGeometry, scene) {
  17774. var id = parsedGeometry.id;
  17775. return scene.getGeometryByID(id);
  17776. };
  17777. var parseBox = function (parsedBox, scene) {
  17778. if (parseGeometry(parsedBox, scene)) {
  17779. return null;
  17780. }
  17781. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17782. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17783. scene.pushGeometry(box, true);
  17784. return box;
  17785. };
  17786. var parseSphere = function (parsedSphere, scene) {
  17787. if (parseGeometry(parsedSphere, scene)) {
  17788. return null;
  17789. }
  17790. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  17791. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  17792. scene.pushGeometry(sphere, true);
  17793. return sphere;
  17794. };
  17795. var parseCylinder = function (parsedCylinder, scene) {
  17796. if (parseGeometry(parsedCylinder, scene)) {
  17797. return null;
  17798. }
  17799. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  17800. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  17801. scene.pushGeometry(cylinder, true);
  17802. return cylinder;
  17803. };
  17804. var parseTorus = function (parsedTorus, scene) {
  17805. if (parseGeometry(parsedTorus, scene)) {
  17806. return null;
  17807. }
  17808. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  17809. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  17810. scene.pushGeometry(torus, true);
  17811. return torus;
  17812. };
  17813. var parseGround = function (parsedGround, scene) {
  17814. if (parseGeometry(parsedGround, scene)) {
  17815. return null;
  17816. }
  17817. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  17818. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  17819. scene.pushGeometry(ground, true);
  17820. return ground;
  17821. };
  17822. var parsePlane = function (parsedPlane, scene) {
  17823. if (parseGeometry(parsedPlane, scene)) {
  17824. return null;
  17825. }
  17826. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  17827. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  17828. scene.pushGeometry(plane, true);
  17829. return plane;
  17830. };
  17831. var parseTorusKnot = function (parsedTorusKnot, scene) {
  17832. if (parseGeometry(parsedTorusKnot, scene)) {
  17833. return null;
  17834. }
  17835. 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);
  17836. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  17837. scene.pushGeometry(torusKnot, true);
  17838. return torusKnot;
  17839. };
  17840. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  17841. if (parseGeometry(parsedVertexData, scene)) {
  17842. return null;
  17843. }
  17844. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  17845. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  17846. if (parsedVertexData.delayLoadingFile) {
  17847. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17848. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  17849. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  17850. geometry._delayInfo = [];
  17851. if (parsedVertexData.hasUVs) {
  17852. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17853. }
  17854. if (parsedVertexData.hasUVs2) {
  17855. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17856. }
  17857. if (parsedVertexData.hasColors) {
  17858. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17859. }
  17860. if (parsedVertexData.hasMatricesIndices) {
  17861. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17862. }
  17863. if (parsedVertexData.hasMatricesWeights) {
  17864. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17865. }
  17866. geometry._delayLoadingFunction = importVertexData;
  17867. } else {
  17868. importVertexData(parsedVertexData, geometry);
  17869. }
  17870. scene.pushGeometry(geometry, true);
  17871. return geometry;
  17872. };
  17873. var parseMesh = function (parsedMesh, scene, rootUrl) {
  17874. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  17875. mesh.id = parsedMesh.id;
  17876. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17877. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17878. if (parsedMesh.rotationQuaternion) {
  17879. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17880. } else if (parsedMesh.rotation) {
  17881. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17882. }
  17883. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17884. if (parsedMesh.localMatrix) {
  17885. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17886. } else if (parsedMesh.pivotMatrix) {
  17887. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17888. }
  17889. mesh.setEnabled(parsedMesh.isEnabled);
  17890. mesh.isVisible = parsedMesh.isVisible;
  17891. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17892. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17893. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17894. if (parsedMesh.applyFog !== undefined) {
  17895. mesh.applyFog = parsedMesh.applyFog;
  17896. }
  17897. if (parsedMesh.pickable !== undefined) {
  17898. mesh.isPickable = parsedMesh.pickable;
  17899. }
  17900. if (parsedMesh.alphaIndex !== undefined) {
  17901. mesh.alphaIndex = parsedMesh.alphaIndex;
  17902. }
  17903. mesh.receiveShadows = parsedMesh.receiveShadows;
  17904. mesh.billboardMode = parsedMesh.billboardMode;
  17905. if (parsedMesh.visibility !== undefined) {
  17906. mesh.visibility = parsedMesh.visibility;
  17907. }
  17908. mesh.checkCollisions = parsedMesh.checkCollisions;
  17909. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17910. // Parent
  17911. if (parsedMesh.parentId) {
  17912. mesh._waitingParentId = parsedMesh.parentId;
  17913. }
  17914. // Actions
  17915. if (parsedMesh.actions !== undefined) {
  17916. mesh._waitingActions = parsedMesh.actions;
  17917. }
  17918. // Geometry
  17919. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17920. if (parsedMesh.delayLoadingFile) {
  17921. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17922. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17923. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17924. if (parsedMesh._binaryInfo) {
  17925. mesh._binaryInfo = parsedMesh._binaryInfo;
  17926. }
  17927. mesh._delayInfo = [];
  17928. if (parsedMesh.hasUVs) {
  17929. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17930. }
  17931. if (parsedMesh.hasUVs2) {
  17932. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17933. }
  17934. if (parsedMesh.hasColors) {
  17935. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17936. }
  17937. if (parsedMesh.hasMatricesIndices) {
  17938. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17939. }
  17940. if (parsedMesh.hasMatricesWeights) {
  17941. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17942. }
  17943. mesh._delayLoadingFunction = importGeometry;
  17944. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17945. mesh._checkDelayState();
  17946. }
  17947. } else {
  17948. importGeometry(parsedMesh, mesh);
  17949. }
  17950. // Material
  17951. if (parsedMesh.materialId) {
  17952. mesh.setMaterialByID(parsedMesh.materialId);
  17953. } else {
  17954. mesh.material = null;
  17955. }
  17956. // Skeleton
  17957. if (parsedMesh.skeletonId > -1) {
  17958. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17959. }
  17960. // Physics
  17961. if (parsedMesh.physicsImpostor) {
  17962. if (!scene.isPhysicsEnabled()) {
  17963. scene.enablePhysics();
  17964. }
  17965. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  17966. }
  17967. // Animations
  17968. if (parsedMesh.animations) {
  17969. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17970. var parsedAnimation = parsedMesh.animations[animationIndex];
  17971. mesh.animations.push(parseAnimation(parsedAnimation));
  17972. }
  17973. }
  17974. if (parsedMesh.autoAnimate) {
  17975. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  17976. }
  17977. // Layer Mask
  17978. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17979. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17980. } else {
  17981. mesh.layerMask = 0xFFFFFFFF;
  17982. }
  17983. // Instances
  17984. if (parsedMesh.instances) {
  17985. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17986. var parsedInstance = parsedMesh.instances[index];
  17987. var instance = mesh.createInstance(parsedInstance.name);
  17988. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17989. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17990. if (parsedInstance.rotationQuaternion) {
  17991. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17992. } else if (parsedInstance.rotation) {
  17993. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17994. }
  17995. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17996. instance.checkCollisions = mesh.checkCollisions;
  17997. if (parsedMesh.animations) {
  17998. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17999. parsedAnimation = parsedMesh.animations[animationIndex];
  18000. instance.animations.push(parseAnimation(parsedAnimation));
  18001. }
  18002. }
  18003. }
  18004. }
  18005. return mesh;
  18006. };
  18007. var parseActions = function (parsedActions, object, scene) {
  18008. object.actionManager = new BABYLON.ActionManager(scene);
  18009. // instanciate a new object
  18010. var instanciate = function (name, params) {
  18011. var newInstance = Object.create(BABYLON[name].prototype);
  18012. newInstance.constructor.apply(newInstance, params);
  18013. return newInstance;
  18014. };
  18015. var parseParameter = function (name, value, target, propertyPath) {
  18016. var split = value.split(",");
  18017. if (split.length == 1) {
  18018. var num = parseFloat(split[0]);
  18019. if (isNaN(num))
  18020. return split[0];
  18021. else
  18022. return num;
  18023. }
  18024. var effectiveTarget = propertyPath.split(".");
  18025. for (var i = 0; i < effectiveTarget.length; i++) {
  18026. target = target[effectiveTarget[i]];
  18027. }
  18028. if (split.length == 3) {
  18029. var values = [parseFloat(split[0]), parseFloat(split[1]), parseFloat(split[2])];
  18030. if (target instanceof BABYLON.Vector3)
  18031. return BABYLON.Vector3.FromArray(values);
  18032. else
  18033. return BABYLON.Color3.FromArray(values);
  18034. }
  18035. if (split.length == 4) {
  18036. var values = [parseFloat(split[0]), parseFloat(split[1]), parseFloat(split[2]), parseFloat(split[3])];
  18037. if (target instanceof BABYLON.Vector4)
  18038. return BABYLON.Vector4.FromArray(values);
  18039. else
  18040. return BABYLON.Color4.FromArray(values);
  18041. }
  18042. };
  18043. // traverse graph per trigger
  18044. var traverse = function (parsedAction, trigger, condition, action, actionManager) {
  18045. var parameters = new Array();
  18046. var target = null;
  18047. var propertyPath = null;
  18048. // Parameters
  18049. if (parsedAction.type == 2)
  18050. parameters.push(actionManager);
  18051. else
  18052. parameters.push(trigger);
  18053. for (var i = 0; i < parsedAction.properties.length; i++) {
  18054. var value = parsedAction.properties[i].value;
  18055. if (parsedAction.properties[i].name === "target") {
  18056. value = target = scene.getNodeByName(value);
  18057. } else if (parsedAction.properties[i].name != "propertyPath") {
  18058. if (value === "false" || value === "true")
  18059. value = value === "true";
  18060. else if (parsedAction.type === 2 && parsedAction.properties[i].name === "operator")
  18061. value = BABYLON.ValueCondition[value];
  18062. else
  18063. value = parseParameter(parsedAction.properties[i].name, value, target, propertyPath);
  18064. } else {
  18065. propertyPath = value;
  18066. }
  18067. parameters.push(value);
  18068. }
  18069. parameters.push(condition);
  18070. // If interpolate value action
  18071. if (parsedAction.name === "InterpolateValueAction") {
  18072. var param = parameters[parameters.length - 2];
  18073. parameters[parameters.length - 1] = param;
  18074. parameters[parameters.length - 2] = condition;
  18075. }
  18076. // Action or condition
  18077. var newAction = instanciate(parsedAction.name, parameters);
  18078. if (newAction instanceof BABYLON.Condition) {
  18079. condition = newAction;
  18080. newAction = action;
  18081. } else {
  18082. condition = null;
  18083. if (action)
  18084. action.then(newAction);
  18085. else
  18086. actionManager.registerAction(newAction);
  18087. }
  18088. for (var i = 0; i < parsedAction.children.length; i++)
  18089. traverse(parsedAction.children[i], trigger, condition, newAction, actionManager);
  18090. };
  18091. for (var i = 0; i < parsedActions.children.length; i++) {
  18092. var triggerParams;
  18093. var trigger = parsedActions.children[i];
  18094. if (trigger.properties.length > 0) {
  18095. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18096. } else
  18097. triggerParams = BABYLON.ActionManager[trigger.name];
  18098. for (var j = 0; j < trigger.children.length; j++)
  18099. traverse(trigger.children[j], triggerParams, null, null, object.actionManager);
  18100. }
  18101. };
  18102. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18103. names = (names instanceof Array) ? names : [names];
  18104. for (var i in names) {
  18105. if (mesh.name === names[i]) {
  18106. hierarchyIds.push(mesh.id);
  18107. return true;
  18108. }
  18109. }
  18110. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18111. hierarchyIds.push(mesh.id);
  18112. return true;
  18113. }
  18114. return false;
  18115. };
  18116. var importVertexData = function (parsedVertexData, geometry) {
  18117. var vertexData = new BABYLON.VertexData();
  18118. // positions
  18119. var positions = parsedVertexData.positions;
  18120. if (positions) {
  18121. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18122. }
  18123. // normals
  18124. var normals = parsedVertexData.normals;
  18125. if (normals) {
  18126. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18127. }
  18128. // uvs
  18129. var uvs = parsedVertexData.uvs;
  18130. if (uvs) {
  18131. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18132. }
  18133. // uv2s
  18134. var uv2s = parsedVertexData.uv2s;
  18135. if (uv2s) {
  18136. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18137. }
  18138. // colors
  18139. var colors = parsedVertexData.colors;
  18140. if (colors) {
  18141. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18142. }
  18143. // matricesIndices
  18144. var matricesIndices = parsedVertexData.matricesIndices;
  18145. if (matricesIndices) {
  18146. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18147. }
  18148. // matricesWeights
  18149. var matricesWeights = parsedVertexData.matricesWeights;
  18150. if (matricesWeights) {
  18151. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18152. }
  18153. // indices
  18154. var indices = parsedVertexData.indices;
  18155. if (indices) {
  18156. vertexData.indices = indices;
  18157. }
  18158. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18159. };
  18160. var importGeometry = function (parsedGeometry, mesh) {
  18161. var scene = mesh.getScene();
  18162. // Geometry
  18163. var geometryId = parsedGeometry.geometryId;
  18164. if (geometryId) {
  18165. var geometry = scene.getGeometryByID(geometryId);
  18166. if (geometry) {
  18167. geometry.applyToMesh(mesh);
  18168. }
  18169. } else if (parsedGeometry instanceof ArrayBuffer) {
  18170. var binaryInfo = mesh._binaryInfo;
  18171. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18172. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18173. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18174. }
  18175. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18176. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18177. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18178. }
  18179. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18180. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18181. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18182. }
  18183. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18184. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18185. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18186. }
  18187. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18188. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18189. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18190. }
  18191. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18192. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18193. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18194. }
  18195. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18196. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18197. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18198. }
  18199. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18200. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18201. mesh.setIndices(indicesData);
  18202. }
  18203. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18204. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18205. mesh.subMeshes = [];
  18206. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18207. var materialIndex = subMeshesData[(i * 5) + 0];
  18208. var verticesStart = subMeshesData[(i * 5) + 1];
  18209. var verticesCount = subMeshesData[(i * 5) + 2];
  18210. var indexStart = subMeshesData[(i * 5) + 3];
  18211. var indexCount = subMeshesData[(i * 5) + 4];
  18212. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18213. }
  18214. }
  18215. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18216. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18217. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18218. if (parsedGeometry.uvs) {
  18219. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18220. }
  18221. if (parsedGeometry.uvs2) {
  18222. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18223. }
  18224. if (parsedGeometry.colors) {
  18225. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18226. }
  18227. if (parsedGeometry.matricesIndices) {
  18228. if (!parsedGeometry.matricesIndices._isExpanded) {
  18229. var floatIndices = [];
  18230. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18231. var matricesIndex = parsedGeometry.matricesIndices[i];
  18232. floatIndices.push(matricesIndex & 0x000000FF);
  18233. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18234. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18235. floatIndices.push(matricesIndex >> 24);
  18236. }
  18237. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18238. } else {
  18239. delete parsedGeometry.matricesIndices._isExpanded;
  18240. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18241. }
  18242. }
  18243. if (parsedGeometry.matricesWeights) {
  18244. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18245. }
  18246. mesh.setIndices(parsedGeometry.indices);
  18247. // SubMeshes
  18248. if (parsedGeometry.subMeshes) {
  18249. mesh.subMeshes = [];
  18250. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18251. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18252. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18253. }
  18254. }
  18255. }
  18256. // Flat shading
  18257. if (mesh._shouldGenerateFlatShading) {
  18258. mesh.convertToFlatShadedMesh();
  18259. delete mesh._shouldGenerateFlatShading;
  18260. }
  18261. // Update
  18262. mesh.computeWorldMatrix(true);
  18263. // Octree
  18264. if (scene._selectionOctree) {
  18265. scene._selectionOctree.addMesh(mesh);
  18266. }
  18267. };
  18268. BABYLON.SceneLoader.RegisterPlugin({
  18269. extensions: ".babylon",
  18270. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18271. var parsedData = JSON.parse(data);
  18272. var loadedSkeletonsIds = [];
  18273. var loadedMaterialsIds = [];
  18274. var hierarchyIds = [];
  18275. for (var index = 0; index < parsedData.meshes.length; index++) {
  18276. var parsedMesh = parsedData.meshes[index];
  18277. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18278. if (meshesNames instanceof Array) {
  18279. // Remove found mesh name from list.
  18280. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18281. }
  18282. // Material ?
  18283. if (parsedMesh.materialId) {
  18284. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18285. if (!materialFound) {
  18286. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18287. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18288. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18289. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18290. var subMatId = parsedMultiMaterial.materials[matIndex];
  18291. loadedMaterialsIds.push(subMatId);
  18292. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18293. }
  18294. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18295. parseMultiMaterial(parsedMultiMaterial, scene);
  18296. materialFound = true;
  18297. break;
  18298. }
  18299. }
  18300. }
  18301. if (!materialFound) {
  18302. loadedMaterialsIds.push(parsedMesh.materialId);
  18303. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18304. }
  18305. }
  18306. // Skeleton ?
  18307. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18308. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  18309. if (!skeletonAlreadyLoaded) {
  18310. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  18311. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  18312. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  18313. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  18314. loadedSkeletonsIds.push(parsedSkeleton.id);
  18315. }
  18316. }
  18317. }
  18318. }
  18319. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  18320. meshes.push(mesh);
  18321. }
  18322. }
  18323. for (index = 0; index < scene.meshes.length; index++) {
  18324. var currentMesh = scene.meshes[index];
  18325. if (currentMesh._waitingParentId) {
  18326. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  18327. currentMesh._waitingParentId = undefined;
  18328. }
  18329. }
  18330. // Particles
  18331. if (parsedData.particleSystems) {
  18332. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18333. var parsedParticleSystem = parsedData.particleSystems[index];
  18334. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  18335. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  18336. }
  18337. }
  18338. }
  18339. return true;
  18340. },
  18341. load: function (scene, data, rootUrl) {
  18342. var parsedData = JSON.parse(data);
  18343. // Scene
  18344. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  18345. scene.autoClear = parsedData.autoClear;
  18346. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  18347. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  18348. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  18349. // Fog
  18350. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  18351. scene.fogMode = parsedData.fogMode;
  18352. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  18353. scene.fogStart = parsedData.fogStart;
  18354. scene.fogEnd = parsedData.fogEnd;
  18355. scene.fogDensity = parsedData.fogDensity;
  18356. }
  18357. for (var index = 0; index < parsedData.lights.length; index++) {
  18358. var parsedLight = parsedData.lights[index];
  18359. parseLight(parsedLight, scene);
  18360. }
  18361. // Materials
  18362. if (parsedData.materials) {
  18363. for (index = 0; index < parsedData.materials.length; index++) {
  18364. var parsedMaterial = parsedData.materials[index];
  18365. parseMaterial(parsedMaterial, scene, rootUrl);
  18366. }
  18367. }
  18368. if (parsedData.multiMaterials) {
  18369. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  18370. var parsedMultiMaterial = parsedData.multiMaterials[index];
  18371. parseMultiMaterial(parsedMultiMaterial, scene);
  18372. }
  18373. }
  18374. // Skeletons
  18375. if (parsedData.skeletons) {
  18376. for (index = 0; index < parsedData.skeletons.length; index++) {
  18377. var parsedSkeleton = parsedData.skeletons[index];
  18378. parseSkeleton(parsedSkeleton, scene);
  18379. }
  18380. }
  18381. // Geometries
  18382. var geometries = parsedData.geometries;
  18383. if (geometries) {
  18384. // Boxes
  18385. var boxes = geometries.boxes;
  18386. if (boxes) {
  18387. for (index = 0; index < boxes.length; index++) {
  18388. var parsedBox = boxes[index];
  18389. parseBox(parsedBox, scene);
  18390. }
  18391. }
  18392. // Spheres
  18393. var spheres = geometries.spheres;
  18394. if (spheres) {
  18395. for (index = 0; index < spheres.length; index++) {
  18396. var parsedSphere = spheres[index];
  18397. parseSphere(parsedSphere, scene);
  18398. }
  18399. }
  18400. // Cylinders
  18401. var cylinders = geometries.cylinders;
  18402. if (cylinders) {
  18403. for (index = 0; index < cylinders.length; index++) {
  18404. var parsedCylinder = cylinders[index];
  18405. parseCylinder(parsedCylinder, scene);
  18406. }
  18407. }
  18408. // Toruses
  18409. var toruses = geometries.toruses;
  18410. if (toruses) {
  18411. for (index = 0; index < toruses.length; index++) {
  18412. var parsedTorus = toruses[index];
  18413. parseTorus(parsedTorus, scene);
  18414. }
  18415. }
  18416. // Grounds
  18417. var grounds = geometries.grounds;
  18418. if (grounds) {
  18419. for (index = 0; index < grounds.length; index++) {
  18420. var parsedGround = grounds[index];
  18421. parseGround(parsedGround, scene);
  18422. }
  18423. }
  18424. // Planes
  18425. var planes = geometries.planes;
  18426. if (planes) {
  18427. for (index = 0; index < planes.length; index++) {
  18428. var parsedPlane = planes[index];
  18429. parsePlane(parsedPlane, scene);
  18430. }
  18431. }
  18432. // TorusKnots
  18433. var torusKnots = geometries.torusKnots;
  18434. if (torusKnots) {
  18435. for (index = 0; index < torusKnots.length; index++) {
  18436. var parsedTorusKnot = torusKnots[index];
  18437. parseTorusKnot(parsedTorusKnot, scene);
  18438. }
  18439. }
  18440. // VertexData
  18441. var vertexData = geometries.vertexData;
  18442. if (vertexData) {
  18443. for (index = 0; index < vertexData.length; index++) {
  18444. var parsedVertexData = vertexData[index];
  18445. parseVertexData(parsedVertexData, scene, rootUrl);
  18446. }
  18447. }
  18448. }
  18449. for (index = 0; index < parsedData.meshes.length; index++) {
  18450. var parsedMesh = parsedData.meshes[index];
  18451. parseMesh(parsedMesh, scene, rootUrl);
  18452. }
  18453. for (index = 0; index < parsedData.cameras.length; index++) {
  18454. var parsedCamera = parsedData.cameras[index];
  18455. parseCamera(parsedCamera, scene);
  18456. }
  18457. if (parsedData.activeCameraID) {
  18458. scene.setActiveCameraByID(parsedData.activeCameraID);
  18459. }
  18460. for (index = 0; index < scene.cameras.length; index++) {
  18461. var camera = scene.cameras[index];
  18462. if (camera._waitingParentId) {
  18463. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18464. camera._waitingParentId = undefined;
  18465. }
  18466. }
  18467. for (index = 0; index < scene.lights.length; index++) {
  18468. var light = scene.lights[index];
  18469. if (light._waitingParentId) {
  18470. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18471. light._waitingParentId = undefined;
  18472. }
  18473. }
  18474. for (index = 0; index < scene.meshes.length; index++) {
  18475. var mesh = scene.meshes[index];
  18476. if (mesh._waitingParentId) {
  18477. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18478. mesh._waitingParentId = undefined;
  18479. }
  18480. if (mesh._waitingActions) {
  18481. parseActions(mesh._waitingActions, mesh, scene);
  18482. mesh._waitingActions = undefined;
  18483. }
  18484. }
  18485. // Particles Systems
  18486. if (parsedData.particleSystems) {
  18487. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18488. var parsedParticleSystem = parsedData.particleSystems[index];
  18489. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18490. }
  18491. }
  18492. // Lens flares
  18493. if (parsedData.lensFlareSystems) {
  18494. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18495. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18496. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18497. }
  18498. }
  18499. // Shadows
  18500. if (parsedData.shadowGenerators) {
  18501. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18502. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18503. parseShadowGenerator(parsedShadowGenerator, scene);
  18504. }
  18505. }
  18506. // Actions (scene)
  18507. if (parsedData.actions) {
  18508. parseActions(parsedData.actions, scene, scene);
  18509. }
  18510. // Finish
  18511. return true;
  18512. }
  18513. });
  18514. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18515. var Internals = BABYLON.Internals;
  18516. })(BABYLON || (BABYLON = {}));
  18517. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18518. var BABYLON;
  18519. (function (BABYLON) {
  18520. // Unique ID when we import meshes from Babylon to CSG
  18521. var currentCSGMeshId = 0;
  18522. // # class Vertex
  18523. // Represents a vertex of a polygon. Use your own vertex class instead of this
  18524. // one to provide additional features like texture coordinates and vertex
  18525. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  18526. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  18527. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  18528. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  18529. // is not used anywhere else.
  18530. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  18531. var Vertex = (function () {
  18532. function Vertex(pos, normal, uv) {
  18533. this.pos = pos;
  18534. this.normal = normal;
  18535. this.uv = uv;
  18536. }
  18537. Vertex.prototype.clone = function () {
  18538. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  18539. };
  18540. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  18541. // orientation of a polygon is flipped.
  18542. Vertex.prototype.flip = function () {
  18543. this.normal = this.normal.scale(-1);
  18544. };
  18545. // Create a new vertex between this vertex and `other` by linearly
  18546. // interpolating all properties using a parameter of `t`. Subclasses should
  18547. // override this to interpolate additional properties.
  18548. Vertex.prototype.interpolate = function (other, t) {
  18549. 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));
  18550. };
  18551. return Vertex;
  18552. })();
  18553. // # class Plane
  18554. // Represents a plane in 3D space.
  18555. var Plane = (function () {
  18556. function Plane(normal, w) {
  18557. this.normal = normal;
  18558. this.w = w;
  18559. }
  18560. Plane.FromPoints = function (a, b, c) {
  18561. var v0 = c.subtract(a);
  18562. var v1 = b.subtract(a);
  18563. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  18564. return null;
  18565. }
  18566. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  18567. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  18568. };
  18569. Plane.prototype.clone = function () {
  18570. return new Plane(this.normal.clone(), this.w);
  18571. };
  18572. Plane.prototype.flip = function () {
  18573. this.normal.scaleInPlace(-1);
  18574. this.w = -this.w;
  18575. };
  18576. // Split `polygon` by this plane if needed, then put the polygon or polygon
  18577. // fragments in the appropriate lists. Coplanar polygons go into either
  18578. // `coplanarFront` or `coplanarBack` depending on their orientation with
  18579. // respect to this plane. Polygons in front or in back of this plane go into
  18580. // either `front` or `back`.
  18581. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  18582. var COPLANAR = 0;
  18583. var FRONT = 1;
  18584. var BACK = 2;
  18585. var SPANNING = 3;
  18586. // Classify each point as well as the entire polygon into one of the above
  18587. // four classes.
  18588. var polygonType = 0;
  18589. var types = [];
  18590. for (var i = 0; i < polygon.vertices.length; i++) {
  18591. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  18592. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  18593. polygonType |= type;
  18594. types.push(type);
  18595. }
  18596. switch (polygonType) {
  18597. case COPLANAR:
  18598. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  18599. break;
  18600. case FRONT:
  18601. front.push(polygon);
  18602. break;
  18603. case BACK:
  18604. back.push(polygon);
  18605. break;
  18606. case SPANNING:
  18607. var f = [], b = [];
  18608. for (i = 0; i < polygon.vertices.length; i++) {
  18609. var j = (i + 1) % polygon.vertices.length;
  18610. var ti = types[i], tj = types[j];
  18611. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  18612. if (ti != BACK)
  18613. f.push(vi);
  18614. if (ti != FRONT)
  18615. b.push(ti != BACK ? vi.clone() : vi);
  18616. if ((ti | tj) == SPANNING) {
  18617. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  18618. var v = vi.interpolate(vj, t);
  18619. f.push(v);
  18620. b.push(v.clone());
  18621. }
  18622. }
  18623. if (f.length >= 3) {
  18624. var poly = new Polygon(f, polygon.shared);
  18625. if (poly.plane)
  18626. front.push(poly);
  18627. }
  18628. if (b.length >= 3) {
  18629. poly = new Polygon(b, polygon.shared);
  18630. if (poly.plane)
  18631. back.push(poly);
  18632. }
  18633. break;
  18634. }
  18635. };
  18636. Plane.EPSILON = 1e-5;
  18637. return Plane;
  18638. })();
  18639. // # class Polygon
  18640. // Represents a convex polygon. The vertices used to initialize a polygon must
  18641. // be coplanar and form a convex loop.
  18642. //
  18643. // Each convex polygon has a `shared` property, which is shared between all
  18644. // polygons that are clones of each other or were split from the same polygon.
  18645. // This can be used to define per-polygon properties (such as surface color).
  18646. var Polygon = (function () {
  18647. function Polygon(vertices, shared) {
  18648. this.vertices = vertices;
  18649. this.shared = shared;
  18650. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  18651. }
  18652. Polygon.prototype.clone = function () {
  18653. var vertices = this.vertices.map(function (v) {
  18654. return v.clone();
  18655. });
  18656. return new Polygon(vertices, this.shared);
  18657. };
  18658. Polygon.prototype.flip = function () {
  18659. this.vertices.reverse().map(function (v) {
  18660. v.flip();
  18661. });
  18662. this.plane.flip();
  18663. };
  18664. return Polygon;
  18665. })();
  18666. // # class Node
  18667. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  18668. // by picking a polygon to split along. That polygon (and all other coplanar
  18669. // polygons) are added directly to that node and the other polygons are added to
  18670. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  18671. // no distinction between internal and leaf nodes.
  18672. var Node = (function () {
  18673. function Node(polygons) {
  18674. this.plane = null;
  18675. this.front = null;
  18676. this.back = null;
  18677. this.polygons = [];
  18678. if (polygons) {
  18679. this.build(polygons);
  18680. }
  18681. }
  18682. Node.prototype.clone = function () {
  18683. var node = new Node();
  18684. node.plane = this.plane && this.plane.clone();
  18685. node.front = this.front && this.front.clone();
  18686. node.back = this.back && this.back.clone();
  18687. node.polygons = this.polygons.map(function (p) {
  18688. return p.clone();
  18689. });
  18690. return node;
  18691. };
  18692. // Convert solid space to empty space and empty space to solid space.
  18693. Node.prototype.invert = function () {
  18694. for (var i = 0; i < this.polygons.length; i++) {
  18695. this.polygons[i].flip();
  18696. }
  18697. if (this.plane) {
  18698. this.plane.flip();
  18699. }
  18700. if (this.front) {
  18701. this.front.invert();
  18702. }
  18703. if (this.back) {
  18704. this.back.invert();
  18705. }
  18706. var temp = this.front;
  18707. this.front = this.back;
  18708. this.back = temp;
  18709. };
  18710. // Recursively remove all polygons in `polygons` that are inside this BSP
  18711. // tree.
  18712. Node.prototype.clipPolygons = function (polygons) {
  18713. if (!this.plane)
  18714. return polygons.slice();
  18715. var front = [], back = [];
  18716. for (var i = 0; i < polygons.length; i++) {
  18717. this.plane.splitPolygon(polygons[i], front, back, front, back);
  18718. }
  18719. if (this.front) {
  18720. front = this.front.clipPolygons(front);
  18721. }
  18722. if (this.back) {
  18723. back = this.back.clipPolygons(back);
  18724. } else {
  18725. back = [];
  18726. }
  18727. return front.concat(back);
  18728. };
  18729. // Remove all polygons in this BSP tree that are inside the other BSP tree
  18730. // `bsp`.
  18731. Node.prototype.clipTo = function (bsp) {
  18732. this.polygons = bsp.clipPolygons(this.polygons);
  18733. if (this.front)
  18734. this.front.clipTo(bsp);
  18735. if (this.back)
  18736. this.back.clipTo(bsp);
  18737. };
  18738. // Return a list of all polygons in this BSP tree.
  18739. Node.prototype.allPolygons = function () {
  18740. var polygons = this.polygons.slice();
  18741. if (this.front)
  18742. polygons = polygons.concat(this.front.allPolygons());
  18743. if (this.back)
  18744. polygons = polygons.concat(this.back.allPolygons());
  18745. return polygons;
  18746. };
  18747. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  18748. // new polygons are filtered down to the bottom of the tree and become new
  18749. // nodes there. Each set of polygons is partitioned using the first polygon
  18750. // (no heuristic is used to pick a good split).
  18751. Node.prototype.build = function (polygons) {
  18752. if (!polygons.length)
  18753. return;
  18754. if (!this.plane)
  18755. this.plane = polygons[0].plane.clone();
  18756. var front = [], back = [];
  18757. for (var i = 0; i < polygons.length; i++) {
  18758. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  18759. }
  18760. if (front.length) {
  18761. if (!this.front)
  18762. this.front = new Node();
  18763. this.front.build(front);
  18764. }
  18765. if (back.length) {
  18766. if (!this.back)
  18767. this.back = new Node();
  18768. this.back.build(back);
  18769. }
  18770. };
  18771. return Node;
  18772. })();
  18773. var CSG = (function () {
  18774. function CSG() {
  18775. this.polygons = new Array();
  18776. }
  18777. // Convert BABYLON.Mesh to BABYLON.CSG
  18778. CSG.FromMesh = function (mesh) {
  18779. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  18780. if (mesh instanceof BABYLON.Mesh) {
  18781. mesh.computeWorldMatrix(true);
  18782. var matrix = mesh.getWorldMatrix();
  18783. var meshPosition = mesh.position.clone();
  18784. var meshRotation = mesh.rotation.clone();
  18785. var meshScaling = mesh.scaling.clone();
  18786. } else {
  18787. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  18788. }
  18789. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18790. var subMeshes = mesh.subMeshes;
  18791. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  18792. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  18793. vertices = [];
  18794. for (var j = 0; j < 3; j++) {
  18795. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  18796. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  18797. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  18798. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  18799. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  18800. vertex = new Vertex(position, normal, uv);
  18801. vertices.push(vertex);
  18802. }
  18803. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  18804. // To handle the case of degenerated triangle
  18805. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  18806. if (polygon.plane)
  18807. polygons.push(polygon);
  18808. }
  18809. }
  18810. var csg = CSG.FromPolygons(polygons);
  18811. csg.matrix = matrix;
  18812. csg.position = meshPosition;
  18813. csg.rotation = meshRotation;
  18814. csg.scaling = meshScaling;
  18815. currentCSGMeshId++;
  18816. return csg;
  18817. };
  18818. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  18819. CSG.FromPolygons = function (polygons) {
  18820. var csg = new BABYLON.CSG();
  18821. csg.polygons = polygons;
  18822. return csg;
  18823. };
  18824. CSG.prototype.clone = function () {
  18825. var csg = new BABYLON.CSG();
  18826. csg.polygons = this.polygons.map(function (p) {
  18827. return p.clone();
  18828. });
  18829. csg.copyTransformAttributes(this);
  18830. return csg;
  18831. };
  18832. CSG.prototype.toPolygons = function () {
  18833. return this.polygons;
  18834. };
  18835. CSG.prototype.union = function (csg) {
  18836. var a = new Node(this.clone().polygons);
  18837. var b = new Node(csg.clone().polygons);
  18838. a.clipTo(b);
  18839. b.clipTo(a);
  18840. b.invert();
  18841. b.clipTo(a);
  18842. b.invert();
  18843. a.build(b.allPolygons());
  18844. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18845. };
  18846. CSG.prototype.unionInPlace = function (csg) {
  18847. var a = new Node(this.polygons);
  18848. var b = new Node(csg.polygons);
  18849. a.clipTo(b);
  18850. b.clipTo(a);
  18851. b.invert();
  18852. b.clipTo(a);
  18853. b.invert();
  18854. a.build(b.allPolygons());
  18855. this.polygons = a.allPolygons();
  18856. };
  18857. CSG.prototype.subtract = function (csg) {
  18858. var a = new Node(this.clone().polygons);
  18859. var b = new Node(csg.clone().polygons);
  18860. a.invert();
  18861. a.clipTo(b);
  18862. b.clipTo(a);
  18863. b.invert();
  18864. b.clipTo(a);
  18865. b.invert();
  18866. a.build(b.allPolygons());
  18867. a.invert();
  18868. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18869. };
  18870. CSG.prototype.subtractInPlace = function (csg) {
  18871. var a = new Node(this.polygons);
  18872. var b = new Node(csg.polygons);
  18873. a.invert();
  18874. a.clipTo(b);
  18875. b.clipTo(a);
  18876. b.invert();
  18877. b.clipTo(a);
  18878. b.invert();
  18879. a.build(b.allPolygons());
  18880. a.invert();
  18881. this.polygons = a.allPolygons();
  18882. };
  18883. CSG.prototype.intersect = function (csg) {
  18884. var a = new Node(this.clone().polygons);
  18885. var b = new Node(csg.clone().polygons);
  18886. a.invert();
  18887. b.clipTo(a);
  18888. b.invert();
  18889. a.clipTo(b);
  18890. b.clipTo(a);
  18891. a.build(b.allPolygons());
  18892. a.invert();
  18893. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18894. };
  18895. CSG.prototype.intersectInPlace = function (csg) {
  18896. var a = new Node(this.polygons);
  18897. var b = new Node(csg.polygons);
  18898. a.invert();
  18899. b.clipTo(a);
  18900. b.invert();
  18901. a.clipTo(b);
  18902. b.clipTo(a);
  18903. a.build(b.allPolygons());
  18904. a.invert();
  18905. this.polygons = a.allPolygons();
  18906. };
  18907. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  18908. // not modified.
  18909. CSG.prototype.inverse = function () {
  18910. var csg = this.clone();
  18911. csg.inverseInPlace();
  18912. return csg;
  18913. };
  18914. CSG.prototype.inverseInPlace = function () {
  18915. this.polygons.map(function (p) {
  18916. p.flip();
  18917. });
  18918. };
  18919. // This is used to keep meshes transformations so they can be restored
  18920. // when we build back a Babylon Mesh
  18921. // NB : All CSG operations are performed in world coordinates
  18922. CSG.prototype.copyTransformAttributes = function (csg) {
  18923. this.matrix = csg.matrix;
  18924. this.position = csg.position;
  18925. this.rotation = csg.rotation;
  18926. this.scaling = csg.scaling;
  18927. return this;
  18928. };
  18929. // Build Raw mesh from CSG
  18930. // Coordinates here are in world space
  18931. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  18932. var matrix = this.matrix.clone();
  18933. matrix.invert();
  18934. 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;
  18935. if (keepSubMeshes) {
  18936. // Sort Polygons, since subMeshes are indices range
  18937. polygons.sort(function (a, b) {
  18938. if (a.shared.meshId === b.shared.meshId) {
  18939. return a.shared.subMeshId - b.shared.subMeshId;
  18940. } else {
  18941. return a.shared.meshId - b.shared.meshId;
  18942. }
  18943. });
  18944. }
  18945. for (var i = 0, il = polygons.length; i < il; i++) {
  18946. polygon = polygons[i];
  18947. // Building SubMeshes
  18948. if (!subMesh_dict[polygon.shared.meshId]) {
  18949. subMesh_dict[polygon.shared.meshId] = {};
  18950. }
  18951. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  18952. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  18953. indexStart: +Infinity,
  18954. indexEnd: -Infinity,
  18955. materialIndex: polygon.shared.materialIndex
  18956. };
  18957. }
  18958. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  18959. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  18960. polygonIndices[0] = 0;
  18961. polygonIndices[1] = j - 1;
  18962. polygonIndices[2] = j;
  18963. for (var k = 0; k < 3; k++) {
  18964. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  18965. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  18966. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  18967. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  18968. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  18969. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  18970. // Check if 2 points can be merged
  18971. 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)) {
  18972. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  18973. uvs.push(uv.x, uv.y);
  18974. normals.push(normal.x, normal.y, normal.z);
  18975. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  18976. }
  18977. indices.push(vertex_idx);
  18978. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  18979. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  18980. currentIndex++;
  18981. }
  18982. }
  18983. }
  18984. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  18985. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18986. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  18987. mesh.setIndices(indices);
  18988. if (keepSubMeshes) {
  18989. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  18990. var materialIndexOffset = 0, materialMaxIndex;
  18991. mesh.subMeshes.length = 0;
  18992. for (var m in subMesh_dict) {
  18993. materialMaxIndex = -1;
  18994. for (var sm in subMesh_dict[m]) {
  18995. subMesh_obj = subMesh_dict[m][sm];
  18996. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  18997. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  18998. }
  18999. materialIndexOffset += ++materialMaxIndex;
  19000. }
  19001. }
  19002. return mesh;
  19003. };
  19004. // Build Mesh from CSG taking material and transforms into account
  19005. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19006. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19007. mesh.material = material;
  19008. mesh.position.copyFrom(this.position);
  19009. mesh.rotation.copyFrom(this.rotation);
  19010. mesh.scaling.copyFrom(this.scaling);
  19011. mesh.computeWorldMatrix(true);
  19012. return mesh;
  19013. };
  19014. return CSG;
  19015. })();
  19016. BABYLON.CSG = CSG;
  19017. })(BABYLON || (BABYLON = {}));
  19018. //# sourceMappingURL=babylon.csg.js.map
  19019. var BABYLON;
  19020. (function (BABYLON) {
  19021. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19022. __extends(OculusDistortionCorrectionPostProcess, _super);
  19023. //ANY
  19024. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19025. var _this = this;
  19026. _super.call(this, name, "oculusDistortionCorrection", [
  19027. 'LensCenter',
  19028. 'Scale',
  19029. 'ScaleIn',
  19030. 'HmdWarpParam'
  19031. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19032. this._isRightEye = isRightEye;
  19033. this._distortionFactors = cameraSettings.DistortionK;
  19034. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19035. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19036. this.onSizeChanged = function () {
  19037. _this.aspectRatio = _this.width * .5 / _this.height;
  19038. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19039. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19040. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19041. };
  19042. this.onApply = function (effect) {
  19043. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19044. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19045. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19046. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19047. };
  19048. }
  19049. return OculusDistortionCorrectionPostProcess;
  19050. })(BABYLON.PostProcess);
  19051. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19052. })(BABYLON || (BABYLON = {}));
  19053. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  19054. // Mainly based on these 2 articles :
  19055. // 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
  19056. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19057. var BABYLON;
  19058. (function (BABYLON) {
  19059. (function (JoystickAxis) {
  19060. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19061. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19062. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19063. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19064. var JoystickAxis = BABYLON.JoystickAxis;
  19065. var VirtualJoystick = (function () {
  19066. function VirtualJoystick(leftJoystick) {
  19067. var _this = this;
  19068. if (leftJoystick) {
  19069. this._leftJoystick = true;
  19070. } else {
  19071. this._leftJoystick = false;
  19072. }
  19073. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19074. VirtualJoystick._globalJoystickIndex++;
  19075. // By default left & right arrow keys are moving the X
  19076. // and up & down keys are moving the Y
  19077. this._axisTargetedByLeftAndRight = 0 /* X */;
  19078. this._axisTargetedByUpAndDown = 1 /* Y */;
  19079. this.reverseLeftRight = false;
  19080. this.reverseUpDown = false;
  19081. // collections of pointers
  19082. this._touches = new BABYLON.VirtualJoystick.Collection();
  19083. this.deltaPosition = BABYLON.Vector3.Zero();
  19084. this._joystickSensibility = 25;
  19085. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19086. this._rotationSpeed = 25;
  19087. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19088. this._rotateOnAxisRelativeToMesh = false;
  19089. // injecting a canvas element on top of the canvas 3D game
  19090. if (!VirtualJoystick.vjCanvas) {
  19091. window.addEventListener("resize", function () {
  19092. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19093. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19094. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19095. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19096. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19097. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19098. }, false);
  19099. VirtualJoystick.vjCanvas = document.createElement("canvas");
  19100. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19101. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19102. VirtualJoystick.vjCanvas.width = window.innerWidth;
  19103. VirtualJoystick.vjCanvas.height = window.innerHeight;
  19104. VirtualJoystick.vjCanvas.style.width = "100%";
  19105. VirtualJoystick.vjCanvas.style.height = "100%";
  19106. VirtualJoystick.vjCanvas.style.position = "absolute";
  19107. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  19108. VirtualJoystick.vjCanvas.style.top = "0px";
  19109. VirtualJoystick.vjCanvas.style.left = "0px";
  19110. VirtualJoystick.vjCanvas.style.zIndex = "5";
  19111. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  19112. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  19113. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  19114. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19115. document.body.appendChild(VirtualJoystick.vjCanvas);
  19116. }
  19117. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  19118. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  19119. this.pressed = false;
  19120. // default joystick color
  19121. this._joystickColor = "cyan";
  19122. this._joystickPointerID = -1;
  19123. // current joystick position
  19124. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  19125. // origin joystick position
  19126. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  19127. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  19128. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  19129. _this._onPointerDown(evt);
  19130. }, false);
  19131. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  19132. _this._onPointerMove(evt);
  19133. }, false);
  19134. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  19135. _this._onPointerUp(evt);
  19136. }, false);
  19137. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  19138. _this._onPointerUp(evt);
  19139. }, false);
  19140. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  19141. evt.preventDefault(); // Disables system menu
  19142. }, false);
  19143. requestAnimationFrame(function () {
  19144. _this._drawVirtualJoystick();
  19145. });
  19146. }
  19147. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  19148. this._joystickSensibility = newJoystickSensibility;
  19149. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19150. };
  19151. VirtualJoystick.prototype._onPointerDown = function (e) {
  19152. var positionOnScreenCondition;
  19153. e.preventDefault();
  19154. if (this._leftJoystick === true) {
  19155. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  19156. } else {
  19157. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  19158. }
  19159. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  19160. // First contact will be dedicated to the virtual joystick
  19161. this._joystickPointerID = e.pointerId;
  19162. this._joystickPointerStartPos.x = e.clientX;
  19163. this._joystickPointerStartPos.y = e.clientY;
  19164. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  19165. this._deltaJoystickVector.x = 0;
  19166. this._deltaJoystickVector.y = 0;
  19167. this.pressed = true;
  19168. this._touches.add(e.pointerId.toString(), e);
  19169. } else {
  19170. // You can only trigger the action buttons with a joystick declared
  19171. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  19172. this._action();
  19173. this._touches.add(e.pointerId.toString(), e);
  19174. }
  19175. }
  19176. };
  19177. VirtualJoystick.prototype._onPointerMove = function (e) {
  19178. // If the current pointer is the one associated to the joystick (first touch contact)
  19179. if (this._joystickPointerID == e.pointerId) {
  19180. this._joystickPointerPos.x = e.clientX;
  19181. this._joystickPointerPos.y = e.clientY;
  19182. this._deltaJoystickVector = this._joystickPointerPos.clone();
  19183. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  19184. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  19185. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  19186. switch (this._axisTargetedByLeftAndRight) {
  19187. case 0 /* X */:
  19188. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  19189. break;
  19190. case 1 /* Y */:
  19191. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  19192. break;
  19193. case 2 /* Z */:
  19194. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  19195. break;
  19196. }
  19197. var directionUpDown = this.reverseUpDown ? 1 : -1;
  19198. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  19199. switch (this._axisTargetedByUpAndDown) {
  19200. case 0 /* X */:
  19201. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  19202. break;
  19203. case 1 /* Y */:
  19204. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  19205. break;
  19206. case 2 /* Z */:
  19207. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  19208. break;
  19209. }
  19210. } else {
  19211. if (this._touches.item(e.pointerId.toString())) {
  19212. this._touches.item(e.pointerId.toString()).x = e.clientX;
  19213. this._touches.item(e.pointerId.toString()).y = e.clientY;
  19214. }
  19215. }
  19216. };
  19217. VirtualJoystick.prototype._onPointerUp = function (e) {
  19218. this._clearCanvas();
  19219. if (this._joystickPointerID == e.pointerId) {
  19220. this._joystickPointerID = -1;
  19221. this.pressed = false;
  19222. }
  19223. this._deltaJoystickVector.x = 0;
  19224. this._deltaJoystickVector.y = 0;
  19225. this._touches.remove(e.pointerId.toString());
  19226. };
  19227. /**
  19228. * Change the color of the virtual joystick
  19229. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  19230. */
  19231. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  19232. this._joystickColor = newColor;
  19233. };
  19234. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  19235. this._action = action;
  19236. };
  19237. // Define which axis you'd like to control for left & right
  19238. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  19239. switch (axis) {
  19240. case 0 /* X */:
  19241. case 1 /* Y */:
  19242. case 2 /* Z */:
  19243. this._axisTargetedByLeftAndRight = axis;
  19244. break;
  19245. default:
  19246. this._axisTargetedByLeftAndRight = 0 /* X */;
  19247. break;
  19248. }
  19249. };
  19250. // Define which axis you'd like to control for up & down
  19251. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  19252. switch (axis) {
  19253. case 0 /* X */:
  19254. case 1 /* Y */:
  19255. case 2 /* Z */:
  19256. this._axisTargetedByUpAndDown = axis;
  19257. break;
  19258. default:
  19259. this._axisTargetedByUpAndDown = 1 /* Y */;
  19260. break;
  19261. }
  19262. };
  19263. VirtualJoystick.prototype._clearCanvas = function () {
  19264. if (this._leftJoystick) {
  19265. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  19266. } else {
  19267. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  19268. }
  19269. };
  19270. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  19271. var _this = this;
  19272. if (this.pressed) {
  19273. this._clearCanvas();
  19274. this._touches.forEach(function (touch) {
  19275. if (touch.pointerId === _this._joystickPointerID) {
  19276. VirtualJoystick.vjCanvasContext.beginPath();
  19277. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19278. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19279. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  19280. VirtualJoystick.vjCanvasContext.stroke();
  19281. VirtualJoystick.vjCanvasContext.beginPath();
  19282. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19283. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19284. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  19285. VirtualJoystick.vjCanvasContext.stroke();
  19286. VirtualJoystick.vjCanvasContext.beginPath();
  19287. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19288. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  19289. VirtualJoystick.vjCanvasContext.stroke();
  19290. } else {
  19291. VirtualJoystick.vjCanvasContext.beginPath();
  19292. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  19293. VirtualJoystick.vjCanvasContext.beginPath();
  19294. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  19295. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19296. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  19297. VirtualJoystick.vjCanvasContext.stroke();
  19298. }
  19299. ;
  19300. });
  19301. }
  19302. requestAnimationFrame(function () {
  19303. _this._drawVirtualJoystick();
  19304. });
  19305. };
  19306. VirtualJoystick.prototype.releaseCanvas = function () {
  19307. if (VirtualJoystick.vjCanvas) {
  19308. document.body.removeChild(VirtualJoystick.vjCanvas);
  19309. VirtualJoystick.vjCanvas = null;
  19310. }
  19311. };
  19312. VirtualJoystick._globalJoystickIndex = 0;
  19313. return VirtualJoystick;
  19314. })();
  19315. BABYLON.VirtualJoystick = VirtualJoystick;
  19316. })(BABYLON || (BABYLON = {}));
  19317. var BABYLON;
  19318. (function (BABYLON) {
  19319. (function (VirtualJoystick) {
  19320. var Collection = (function () {
  19321. function Collection() {
  19322. this._count = 0;
  19323. this._collection = new Array();
  19324. }
  19325. Collection.prototype.Count = function () {
  19326. return this._count;
  19327. };
  19328. Collection.prototype.add = function (key, item) {
  19329. if (this._collection[key] != undefined) {
  19330. return undefined;
  19331. }
  19332. this._collection[key] = item;
  19333. return ++this._count;
  19334. };
  19335. Collection.prototype.remove = function (key) {
  19336. if (this._collection[key] == undefined) {
  19337. return undefined;
  19338. }
  19339. delete this._collection[key];
  19340. return --this._count;
  19341. };
  19342. Collection.prototype.item = function (key) {
  19343. return this._collection[key];
  19344. };
  19345. Collection.prototype.forEach = function (block) {
  19346. var key;
  19347. for (key in this._collection) {
  19348. if (this._collection.hasOwnProperty(key)) {
  19349. block(this._collection[key]);
  19350. }
  19351. }
  19352. };
  19353. return Collection;
  19354. })();
  19355. VirtualJoystick.Collection = Collection;
  19356. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  19357. var VirtualJoystick = BABYLON.VirtualJoystick;
  19358. })(BABYLON || (BABYLON = {}));
  19359. //# sourceMappingURL=babylon.virtualJoystick.js.map
  19360. var BABYLON;
  19361. (function (BABYLON) {
  19362. var OculusRiftDevKit2013_Metric = {
  19363. HResolution: 1280,
  19364. VResolution: 800,
  19365. HScreenSize: 0.149759993,
  19366. VScreenSize: 0.0935999975,
  19367. VScreenCenter: 0.0467999987,
  19368. EyeToScreenDistance: 0.0410000011,
  19369. LensSeparationDistance: 0.0635000020,
  19370. InterpupillaryDistance: 0.0640000030,
  19371. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19372. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19373. PostProcessScaleFactor: 1.714605507808412,
  19374. LensCenterOffset: 0.151976421
  19375. };
  19376. var _OculusInnerCamera = (function (_super) {
  19377. __extends(_OculusInnerCamera, _super);
  19378. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  19379. _super.call(this, name, position, scene);
  19380. this._workMatrix = new BABYLON.Matrix();
  19381. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19382. // Constants
  19383. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19384. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19385. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19386. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19387. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19388. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19389. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19390. // Postprocess
  19391. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19392. }
  19393. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  19394. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19395. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19396. return this._projectionMatrix;
  19397. };
  19398. _OculusInnerCamera.prototype._getViewMatrix = function () {
  19399. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19400. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19401. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19402. // Computing target and final matrix
  19403. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19404. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19405. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19406. return this._viewMatrix;
  19407. };
  19408. return _OculusInnerCamera;
  19409. })(BABYLON.FreeCamera);
  19410. var OculusCamera = (function (_super) {
  19411. __extends(OculusCamera, _super);
  19412. function OculusCamera(name, position, scene) {
  19413. _super.call(this, name, position, scene);
  19414. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  19415. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  19416. this.subCameras.push(this._leftCamera);
  19417. this.subCameras.push(this._rightCamera);
  19418. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19419. }
  19420. OculusCamera.prototype._update = function () {
  19421. this._leftCamera.position.copyFrom(this.position);
  19422. this._rightCamera.position.copyFrom(this.position);
  19423. this._updateCamera(this._leftCamera);
  19424. this._updateCamera(this._rightCamera);
  19425. _super.prototype._update.call(this);
  19426. };
  19427. OculusCamera.prototype._updateCamera = function (camera) {
  19428. camera.minZ = this.minZ;
  19429. camera.maxZ = this.maxZ;
  19430. camera.rotation.x = this.rotation.x;
  19431. camera.rotation.y = this.rotation.y;
  19432. camera.rotation.z = this.rotation.z;
  19433. };
  19434. // Oculus events
  19435. OculusCamera.prototype._onOrientationEvent = function (evt) {
  19436. var yaw = evt.alpha / 180 * Math.PI;
  19437. var pitch = evt.beta / 180 * Math.PI;
  19438. var roll = evt.gamma / 180 * Math.PI;
  19439. if (!this._offsetOrientation) {
  19440. this._offsetOrientation = {
  19441. yaw: yaw,
  19442. pitch: pitch,
  19443. roll: roll
  19444. };
  19445. return;
  19446. } else {
  19447. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19448. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19449. this.rotation.z += this._offsetOrientation.roll - roll;
  19450. this._offsetOrientation.yaw = yaw;
  19451. this._offsetOrientation.pitch = pitch;
  19452. this._offsetOrientation.roll = roll;
  19453. }
  19454. };
  19455. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  19456. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19457. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19458. };
  19459. OculusCamera.prototype.detachControl = function (element) {
  19460. _super.prototype.detachControl.call(this, element);
  19461. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19462. };
  19463. return OculusCamera;
  19464. })(BABYLON.FreeCamera);
  19465. BABYLON.OculusCamera = OculusCamera;
  19466. })(BABYLON || (BABYLON = {}));
  19467. //# sourceMappingURL=babylon.oculusCamera.js.map
  19468. var BABYLON;
  19469. (function (BABYLON) {
  19470. var OculusRiftDevKit2013_Metric = {
  19471. HResolution: 1280,
  19472. VResolution: 800,
  19473. HScreenSize: 0.149759993,
  19474. VScreenSize: 0.0935999975,
  19475. VScreenCenter: 0.0467999987,
  19476. EyeToScreenDistance: 0.0410000011,
  19477. LensSeparationDistance: 0.0635000020,
  19478. InterpupillaryDistance: 0.0640000030,
  19479. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19480. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19481. PostProcessScaleFactor: 1.714605507808412,
  19482. LensCenterOffset: 0.151976421
  19483. };
  19484. var _OculusInnerGamepadCamera = (function (_super) {
  19485. __extends(_OculusInnerGamepadCamera, _super);
  19486. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  19487. _super.call(this, name, position, scene);
  19488. this._workMatrix = new BABYLON.Matrix();
  19489. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19490. // Constants
  19491. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19492. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19493. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19494. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19495. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19496. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19497. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19498. // Postprocess
  19499. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19500. }
  19501. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  19502. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19503. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19504. return this._projectionMatrix;
  19505. };
  19506. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  19507. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19508. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19509. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19510. // Computing target and final matrix
  19511. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19512. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19513. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19514. return this._viewMatrix;
  19515. };
  19516. return _OculusInnerGamepadCamera;
  19517. })(BABYLON.FreeCamera);
  19518. var OculusGamepadCamera = (function (_super) {
  19519. __extends(OculusGamepadCamera, _super);
  19520. function OculusGamepadCamera(name, position, scene) {
  19521. var _this = this;
  19522. _super.call(this, name, position, scene);
  19523. this.angularSensibility = 200;
  19524. this.moveSensibility = 75;
  19525. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  19526. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  19527. this.subCameras.push(this._leftCamera);
  19528. this.subCameras.push(this._rightCamera);
  19529. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19530. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19531. _this._onNewGameConnected(gamepad);
  19532. });
  19533. }
  19534. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19535. // Only the first gamepad can control the camera
  19536. if (gamepad.index === 0) {
  19537. this._gamepad = gamepad;
  19538. }
  19539. };
  19540. OculusGamepadCamera.prototype._update = function () {
  19541. this._leftCamera.position.copyFrom(this.position);
  19542. this._rightCamera.position.copyFrom(this.position);
  19543. this._updateCamera(this._leftCamera);
  19544. this._updateCamera(this._rightCamera);
  19545. _super.prototype._update.call(this);
  19546. };
  19547. OculusGamepadCamera.prototype._checkInputs = function () {
  19548. if (!this._gamepad) {
  19549. return;
  19550. }
  19551. var LSValues = this._gamepad.leftStick;
  19552. var normalizedLX = LSValues.x / this.moveSensibility;
  19553. var normalizedLY = LSValues.y / this.moveSensibility;
  19554. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19555. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19556. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19557. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19558. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19559. };
  19560. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  19561. camera.minZ = this.minZ;
  19562. camera.maxZ = this.maxZ;
  19563. camera.rotation.x = this.rotation.x;
  19564. camera.rotation.y = this.rotation.y;
  19565. camera.rotation.z = this.rotation.z;
  19566. };
  19567. // Oculus events
  19568. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  19569. var yaw = evt.alpha / 180 * Math.PI;
  19570. var pitch = evt.beta / 180 * Math.PI;
  19571. var roll = evt.gamma / 180 * Math.PI;
  19572. if (!this._offsetOrientation) {
  19573. this._offsetOrientation = {
  19574. yaw: yaw,
  19575. pitch: pitch,
  19576. roll: roll
  19577. };
  19578. return;
  19579. } else {
  19580. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19581. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19582. this.rotation.z += this._offsetOrientation.roll - roll;
  19583. this._offsetOrientation.yaw = yaw;
  19584. this._offsetOrientation.pitch = pitch;
  19585. this._offsetOrientation.roll = roll;
  19586. }
  19587. };
  19588. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  19589. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19590. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19591. };
  19592. OculusGamepadCamera.prototype.detachControl = function (element) {
  19593. _super.prototype.detachControl.call(this, element);
  19594. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19595. };
  19596. OculusGamepadCamera.prototype.dispose = function () {
  19597. this._gamepads.dispose();
  19598. _super.prototype.dispose.call(this);
  19599. };
  19600. return OculusGamepadCamera;
  19601. })(BABYLON.FreeCamera);
  19602. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  19603. })(BABYLON || (BABYLON = {}));
  19604. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  19605. var BABYLON;
  19606. (function (BABYLON) {
  19607. // We're mainly based on the logic defined into the FreeCamera code
  19608. var VirtualJoysticksCamera = (function (_super) {
  19609. __extends(VirtualJoysticksCamera, _super);
  19610. function VirtualJoysticksCamera(name, position, scene) {
  19611. _super.call(this, name, position, scene);
  19612. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  19613. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  19614. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  19615. this._leftjoystick.setJoystickSensibility(0.15);
  19616. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  19617. this._rightjoystick.setAxisForUpDown(0 /* X */);
  19618. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  19619. this._rightjoystick.reverseUpDown = true;
  19620. this._rightjoystick.setJoystickSensibility(0.05);
  19621. this._rightjoystick.setJoystickColor("yellow");
  19622. }
  19623. VirtualJoysticksCamera.prototype._checkInputs = function () {
  19624. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19625. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  19626. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19627. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  19628. if (!this._leftjoystick.pressed) {
  19629. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  19630. }
  19631. if (!this._rightjoystick.pressed) {
  19632. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  19633. }
  19634. };
  19635. VirtualJoysticksCamera.prototype.dispose = function () {
  19636. this._leftjoystick.releaseCanvas();
  19637. _super.prototype.dispose.call(this);
  19638. };
  19639. return VirtualJoysticksCamera;
  19640. })(BABYLON.FreeCamera);
  19641. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  19642. })(BABYLON || (BABYLON = {}));
  19643. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  19644. var BABYLON;
  19645. (function (BABYLON) {
  19646. var ShaderMaterial = (function (_super) {
  19647. __extends(ShaderMaterial, _super);
  19648. function ShaderMaterial(name, scene, shaderPath, options) {
  19649. _super.call(this, name, scene);
  19650. this._textures = new Array();
  19651. this._floats = new Array();
  19652. this._floatsArrays = {};
  19653. this._colors3 = new Array();
  19654. this._colors4 = new Array();
  19655. this._vectors2 = new Array();
  19656. this._vectors3 = new Array();
  19657. this._matrices = new Array();
  19658. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  19659. this._shaderPath = shaderPath;
  19660. options.needAlphaBlending = options.needAlphaBlending || false;
  19661. options.needAlphaTesting = options.needAlphaTesting || false;
  19662. options.attributes = options.attributes || ["position", "normal", "uv"];
  19663. options.uniforms = options.uniforms || ["worldViewProjection"];
  19664. options.samplers = options.samplers || [];
  19665. this._options = options;
  19666. }
  19667. ShaderMaterial.prototype.needAlphaBlending = function () {
  19668. return this._options.needAlphaBlending;
  19669. };
  19670. ShaderMaterial.prototype.needAlphaTesting = function () {
  19671. return this._options.needAlphaTesting;
  19672. };
  19673. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  19674. if (this._options.uniforms.indexOf(uniformName) === -1) {
  19675. this._options.uniforms.push(uniformName);
  19676. }
  19677. };
  19678. ShaderMaterial.prototype.setTexture = function (name, texture) {
  19679. if (this._options.samplers.indexOf(name) === -1) {
  19680. this._options.samplers.push(name);
  19681. }
  19682. this._textures[name] = texture;
  19683. return this;
  19684. };
  19685. ShaderMaterial.prototype.setFloat = function (name, value) {
  19686. this._checkUniform(name);
  19687. this._floats[name] = value;
  19688. return this;
  19689. };
  19690. ShaderMaterial.prototype.setFloats = function (name, value) {
  19691. this._checkUniform(name);
  19692. this._floatsArrays[name] = value;
  19693. return this;
  19694. };
  19695. ShaderMaterial.prototype.setColor3 = function (name, value) {
  19696. this._checkUniform(name);
  19697. this._colors3[name] = value;
  19698. return this;
  19699. };
  19700. ShaderMaterial.prototype.setColor4 = function (name, value) {
  19701. this._checkUniform(name);
  19702. this._colors4[name] = value;
  19703. return this;
  19704. };
  19705. ShaderMaterial.prototype.setVector2 = function (name, value) {
  19706. this._checkUniform(name);
  19707. this._vectors2[name] = value;
  19708. return this;
  19709. };
  19710. ShaderMaterial.prototype.setVector3 = function (name, value) {
  19711. this._checkUniform(name);
  19712. this._vectors3[name] = value;
  19713. return this;
  19714. };
  19715. ShaderMaterial.prototype.setMatrix = function (name, value) {
  19716. this._checkUniform(name);
  19717. this._matrices[name] = value;
  19718. return this;
  19719. };
  19720. ShaderMaterial.prototype.isReady = function () {
  19721. var scene = this.getScene();
  19722. var engine = scene.getEngine();
  19723. if (!this.checkReadyOnEveryCall) {
  19724. if (this._renderId === scene.getRenderId()) {
  19725. return true;
  19726. }
  19727. }
  19728. var previousEffect = this._effect;
  19729. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  19730. if (!this._effect.isReady()) {
  19731. return false;
  19732. }
  19733. if (previousEffect !== this._effect) {
  19734. scene.resetCachedMaterial();
  19735. }
  19736. this._renderId = scene.getRenderId();
  19737. return true;
  19738. };
  19739. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19740. var scene = this.getScene();
  19741. if (this._options.uniforms.indexOf("world") !== -1) {
  19742. this._effect.setMatrix("world", world);
  19743. }
  19744. if (this._options.uniforms.indexOf("worldView") !== -1) {
  19745. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  19746. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  19747. }
  19748. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  19749. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  19750. }
  19751. };
  19752. ShaderMaterial.prototype.bind = function (world) {
  19753. // Std values
  19754. this.bindOnlyWorldMatrix(world);
  19755. if (this.getScene().getCachedMaterial() !== this) {
  19756. if (this._options.uniforms.indexOf("view") !== -1) {
  19757. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  19758. }
  19759. if (this._options.uniforms.indexOf("projection") !== -1) {
  19760. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  19761. }
  19762. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  19763. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  19764. }
  19765. for (var name in this._textures) {
  19766. this._effect.setTexture(name, this._textures[name]);
  19767. }
  19768. for (name in this._floats) {
  19769. this._effect.setFloat(name, this._floats[name]);
  19770. }
  19771. for (name in this._floatsArrays) {
  19772. this._effect.setArray(name, this._floatsArrays[name]);
  19773. }
  19774. for (name in this._colors3) {
  19775. this._effect.setColor3(name, this._colors3[name]);
  19776. }
  19777. for (name in this._colors4) {
  19778. var color = this._colors4[name];
  19779. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19780. }
  19781. for (name in this._vectors2) {
  19782. this._effect.setVector2(name, this._vectors2[name]);
  19783. }
  19784. for (name in this._vectors3) {
  19785. this._effect.setVector3(name, this._vectors3[name]);
  19786. }
  19787. for (name in this._matrices) {
  19788. this._effect.setMatrix(name, this._matrices[name]);
  19789. }
  19790. }
  19791. _super.prototype.bind.call(this, world, null);
  19792. };
  19793. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  19794. for (var name in this._textures) {
  19795. this._textures[name].dispose();
  19796. }
  19797. this._textures = [];
  19798. _super.prototype.dispose.call(this, forceDisposeEffect);
  19799. };
  19800. return ShaderMaterial;
  19801. })(BABYLON.Material);
  19802. BABYLON.ShaderMaterial = ShaderMaterial;
  19803. })(BABYLON || (BABYLON = {}));
  19804. //# sourceMappingURL=babylon.shaderMaterial.js.map
  19805. var BABYLON;
  19806. (function (BABYLON) {
  19807. var VertexData = (function () {
  19808. function VertexData() {
  19809. }
  19810. VertexData.prototype.set = function (data, kind) {
  19811. switch (kind) {
  19812. case BABYLON.VertexBuffer.PositionKind:
  19813. this.positions = data;
  19814. break;
  19815. case BABYLON.VertexBuffer.NormalKind:
  19816. this.normals = data;
  19817. break;
  19818. case BABYLON.VertexBuffer.UVKind:
  19819. this.uvs = data;
  19820. break;
  19821. case BABYLON.VertexBuffer.UV2Kind:
  19822. this.uv2s = data;
  19823. break;
  19824. case BABYLON.VertexBuffer.ColorKind:
  19825. this.colors = data;
  19826. break;
  19827. case BABYLON.VertexBuffer.MatricesIndicesKind:
  19828. this.matricesIndices = data;
  19829. break;
  19830. case BABYLON.VertexBuffer.MatricesWeightsKind:
  19831. this.matricesWeights = data;
  19832. break;
  19833. }
  19834. };
  19835. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  19836. this._applyTo(mesh, updatable);
  19837. };
  19838. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  19839. this._applyTo(geometry, updatable);
  19840. };
  19841. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  19842. this._update(mesh);
  19843. };
  19844. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  19845. this._update(geometry);
  19846. };
  19847. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  19848. if (this.positions) {
  19849. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  19850. }
  19851. if (this.normals) {
  19852. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  19853. }
  19854. if (this.uvs) {
  19855. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  19856. }
  19857. if (this.uv2s) {
  19858. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  19859. }
  19860. if (this.colors) {
  19861. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  19862. }
  19863. if (this.matricesIndices) {
  19864. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  19865. }
  19866. if (this.matricesWeights) {
  19867. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  19868. }
  19869. if (this.indices) {
  19870. meshOrGeometry.setIndices(this.indices);
  19871. }
  19872. };
  19873. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  19874. if (this.positions) {
  19875. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  19876. }
  19877. if (this.normals) {
  19878. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  19879. }
  19880. if (this.uvs) {
  19881. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  19882. }
  19883. if (this.uv2s) {
  19884. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  19885. }
  19886. if (this.colors) {
  19887. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  19888. }
  19889. if (this.matricesIndices) {
  19890. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  19891. }
  19892. if (this.matricesWeights) {
  19893. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  19894. }
  19895. if (this.indices) {
  19896. meshOrGeometry.setIndices(this.indices);
  19897. }
  19898. };
  19899. VertexData.prototype.transform = function (matrix) {
  19900. var transformed = BABYLON.Vector3.Zero();
  19901. if (this.positions) {
  19902. var position = BABYLON.Vector3.Zero();
  19903. for (var index = 0; index < this.positions.length; index += 3) {
  19904. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  19905. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  19906. this.positions[index] = transformed.x;
  19907. this.positions[index + 1] = transformed.y;
  19908. this.positions[index + 2] = transformed.z;
  19909. }
  19910. }
  19911. if (this.normals) {
  19912. var normal = BABYLON.Vector3.Zero();
  19913. for (index = 0; index < this.normals.length; index += 3) {
  19914. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  19915. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  19916. this.normals[index] = transformed.x;
  19917. this.normals[index + 1] = transformed.y;
  19918. this.normals[index + 2] = transformed.z;
  19919. }
  19920. }
  19921. };
  19922. VertexData.prototype.merge = function (other) {
  19923. if (other.indices) {
  19924. if (!this.indices) {
  19925. this.indices = [];
  19926. }
  19927. var offset = this.positions ? this.positions.length / 3 : 0;
  19928. for (var index = 0; index < other.indices.length; index++) {
  19929. this.indices.push(other.indices[index] + offset);
  19930. }
  19931. }
  19932. if (other.positions) {
  19933. if (!this.positions) {
  19934. this.positions = [];
  19935. }
  19936. for (index = 0; index < other.positions.length; index++) {
  19937. this.positions.push(other.positions[index]);
  19938. }
  19939. }
  19940. if (other.normals) {
  19941. if (!this.normals) {
  19942. this.normals = [];
  19943. }
  19944. for (index = 0; index < other.normals.length; index++) {
  19945. this.normals.push(other.normals[index]);
  19946. }
  19947. }
  19948. if (other.uvs) {
  19949. if (!this.uvs) {
  19950. this.uvs = [];
  19951. }
  19952. for (index = 0; index < other.uvs.length; index++) {
  19953. this.uvs.push(other.uvs[index]);
  19954. }
  19955. }
  19956. if (other.uv2s) {
  19957. if (!this.uv2s) {
  19958. this.uv2s = [];
  19959. }
  19960. for (index = 0; index < other.uv2s.length; index++) {
  19961. this.uv2s.push(other.uv2s[index]);
  19962. }
  19963. }
  19964. if (other.matricesIndices) {
  19965. if (!this.matricesIndices) {
  19966. this.matricesIndices = [];
  19967. }
  19968. for (index = 0; index < other.matricesIndices.length; index++) {
  19969. this.matricesIndices.push(other.matricesIndices[index]);
  19970. }
  19971. }
  19972. if (other.matricesWeights) {
  19973. if (!this.matricesWeights) {
  19974. this.matricesWeights = [];
  19975. }
  19976. for (index = 0; index < other.matricesWeights.length; index++) {
  19977. this.matricesWeights.push(other.matricesWeights[index]);
  19978. }
  19979. }
  19980. if (other.colors) {
  19981. if (!this.colors) {
  19982. this.colors = [];
  19983. }
  19984. for (index = 0; index < other.colors.length; index++) {
  19985. this.colors.push(other.colors[index]);
  19986. }
  19987. }
  19988. };
  19989. // Statics
  19990. VertexData.ExtractFromMesh = function (mesh) {
  19991. return VertexData._ExtractFrom(mesh);
  19992. };
  19993. VertexData.ExtractFromGeometry = function (geometry) {
  19994. return VertexData._ExtractFrom(geometry);
  19995. };
  19996. VertexData._ExtractFrom = function (meshOrGeometry) {
  19997. var result = new BABYLON.VertexData();
  19998. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19999. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20000. }
  20001. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20002. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20003. }
  20004. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20005. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20006. }
  20007. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20008. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20009. }
  20010. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20011. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20012. }
  20013. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20014. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20015. }
  20016. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20017. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20018. }
  20019. result.indices = meshOrGeometry.getIndices();
  20020. return result;
  20021. };
  20022. VertexData.CreateBox = function (size) {
  20023. var normalsSource = [
  20024. new BABYLON.Vector3(0, 0, 1),
  20025. new BABYLON.Vector3(0, 0, -1),
  20026. new BABYLON.Vector3(1, 0, 0),
  20027. new BABYLON.Vector3(-1, 0, 0),
  20028. new BABYLON.Vector3(0, 1, 0),
  20029. new BABYLON.Vector3(0, -1, 0)
  20030. ];
  20031. var indices = [];
  20032. var positions = [];
  20033. var normals = [];
  20034. var uvs = [];
  20035. size = size || 1;
  20036. for (var index = 0; index < normalsSource.length; index++) {
  20037. var normal = normalsSource[index];
  20038. // Get two vectors perpendicular to the face normal and to each other.
  20039. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  20040. var side2 = BABYLON.Vector3.Cross(normal, side1);
  20041. // Six indices (two triangles) per face.
  20042. var verticesLength = positions.length / 3;
  20043. indices.push(verticesLength);
  20044. indices.push(verticesLength + 1);
  20045. indices.push(verticesLength + 2);
  20046. indices.push(verticesLength);
  20047. indices.push(verticesLength + 2);
  20048. indices.push(verticesLength + 3);
  20049. // Four vertices per face.
  20050. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  20051. positions.push(vertex.x, vertex.y, vertex.z);
  20052. normals.push(normal.x, normal.y, normal.z);
  20053. uvs.push(1.0, 1.0);
  20054. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  20055. positions.push(vertex.x, vertex.y, vertex.z);
  20056. normals.push(normal.x, normal.y, normal.z);
  20057. uvs.push(0.0, 1.0);
  20058. vertex = normal.add(side1).add(side2).scale(size / 2);
  20059. positions.push(vertex.x, vertex.y, vertex.z);
  20060. normals.push(normal.x, normal.y, normal.z);
  20061. uvs.push(0.0, 0.0);
  20062. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  20063. positions.push(vertex.x, vertex.y, vertex.z);
  20064. normals.push(normal.x, normal.y, normal.z);
  20065. uvs.push(1.0, 0.0);
  20066. }
  20067. // Result
  20068. var vertexData = new BABYLON.VertexData();
  20069. vertexData.indices = indices;
  20070. vertexData.positions = positions;
  20071. vertexData.normals = normals;
  20072. vertexData.uvs = uvs;
  20073. return vertexData;
  20074. };
  20075. VertexData.CreateSphere = function (segments, diameter) {
  20076. segments = segments || 32;
  20077. diameter = diameter || 1;
  20078. var radius = diameter / 2;
  20079. var totalZRotationSteps = 2 + segments;
  20080. var totalYRotationSteps = 2 * totalZRotationSteps;
  20081. var indices = [];
  20082. var positions = [];
  20083. var normals = [];
  20084. var uvs = [];
  20085. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  20086. var normalizedZ = zRotationStep / totalZRotationSteps;
  20087. var angleZ = (normalizedZ * Math.PI);
  20088. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20089. var normalizedY = yRotationStep / totalYRotationSteps;
  20090. var angleY = normalizedY * Math.PI * 2;
  20091. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20092. var rotationY = BABYLON.Matrix.RotationY(angleY);
  20093. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  20094. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  20095. var vertex = complete.scale(radius);
  20096. var normal = BABYLON.Vector3.Normalize(vertex);
  20097. positions.push(vertex.x, vertex.y, vertex.z);
  20098. normals.push(normal.x, normal.y, normal.z);
  20099. uvs.push(normalizedZ, normalizedY);
  20100. }
  20101. if (zRotationStep > 0) {
  20102. var verticesCount = positions.length / 3;
  20103. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  20104. indices.push((firstIndex));
  20105. indices.push((firstIndex + 1));
  20106. indices.push(firstIndex + totalYRotationSteps + 1);
  20107. indices.push((firstIndex + totalYRotationSteps + 1));
  20108. indices.push((firstIndex + 1));
  20109. indices.push((firstIndex + totalYRotationSteps + 2));
  20110. }
  20111. }
  20112. }
  20113. // Result
  20114. var vertexData = new BABYLON.VertexData();
  20115. vertexData.indices = indices;
  20116. vertexData.positions = positions;
  20117. vertexData.normals = normals;
  20118. vertexData.uvs = uvs;
  20119. return vertexData;
  20120. };
  20121. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  20122. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  20123. var radiusTop = diameterTop / 2;
  20124. var radiusBottom = diameterBottom / 2;
  20125. var indices = [];
  20126. var positions = [];
  20127. var normals = [];
  20128. var uvs = [];
  20129. height = height || 1;
  20130. diameterTop = diameterTop || 0.5;
  20131. diameterBottom = diameterBottom || 1;
  20132. tessellation = tessellation || 16;
  20133. subdivisions = subdivisions || 1;
  20134. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  20135. var getCircleVector = function (i) {
  20136. var angle = (i * 2.0 * Math.PI / tessellation);
  20137. var dx = Math.cos(angle);
  20138. var dz = Math.sin(angle);
  20139. return new BABYLON.Vector3(dx, 0, dz);
  20140. };
  20141. var createCylinderCap = function (isTop) {
  20142. var radius = isTop ? radiusTop : radiusBottom;
  20143. if (radius == 0) {
  20144. return;
  20145. }
  20146. var vbase = positions.length / 3;
  20147. var offset = new BABYLON.Vector3(0, height / 2, 0);
  20148. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  20149. if (!isTop) {
  20150. offset.scaleInPlace(-1);
  20151. textureScale.x = -textureScale.x;
  20152. }
  20153. for (i = 0; i < tessellation; i++) {
  20154. var circleVector = getCircleVector(i);
  20155. var position = circleVector.scale(radius).add(offset);
  20156. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  20157. positions.push(position.x, position.y, position.z);
  20158. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20159. }
  20160. for (var i = 0; i < tessellation - 2; i++) {
  20161. if (!isTop) {
  20162. indices.push(vbase);
  20163. indices.push(vbase + (i + 2) % tessellation);
  20164. indices.push(vbase + (i + 1) % tessellation);
  20165. } else {
  20166. indices.push(vbase);
  20167. indices.push(vbase + (i + 1) % tessellation);
  20168. indices.push(vbase + (i + 2) % tessellation);
  20169. }
  20170. }
  20171. };
  20172. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  20173. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  20174. var stride = tessellation + 1;
  20175. for (var i = 0; i <= tessellation; i++) {
  20176. var circleVector = getCircleVector(i);
  20177. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  20178. var position, radius = radiusBottom;
  20179. for (var s = 0; s <= subdivisions; s++) {
  20180. // Update variables
  20181. position = circleVector.scale(radius);
  20182. position.addInPlace(base.add(offset.scale(s)));
  20183. textureCoordinate.y += 1 / subdivisions;
  20184. radius += (radiusTop - radiusBottom) / subdivisions;
  20185. // Push in arrays
  20186. positions.push(position.x, position.y, position.z);
  20187. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20188. }
  20189. }
  20190. subdivisions += 1;
  20191. for (var s = 0; s < subdivisions - 1; s++) {
  20192. for (var i = 0; i <= tessellation; i++) {
  20193. indices.push(i * subdivisions + s);
  20194. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20195. indices.push(i * subdivisions + (s + 1));
  20196. indices.push(i * subdivisions + (s + 1));
  20197. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20198. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  20199. }
  20200. }
  20201. // Create flat triangle fan caps to seal the top and bottom.
  20202. createCylinderCap(true);
  20203. createCylinderCap(false);
  20204. // Normals
  20205. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20206. // Result
  20207. var vertexData = new BABYLON.VertexData();
  20208. vertexData.indices = indices;
  20209. vertexData.positions = positions;
  20210. vertexData.normals = normals;
  20211. vertexData.uvs = uvs;
  20212. return vertexData;
  20213. };
  20214. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  20215. var indices = [];
  20216. var positions = [];
  20217. var normals = [];
  20218. var uvs = [];
  20219. diameter = diameter || 1;
  20220. thickness = thickness || 0.5;
  20221. tessellation = tessellation || 16;
  20222. var stride = tessellation + 1;
  20223. for (var i = 0; i <= tessellation; i++) {
  20224. var u = i / tessellation;
  20225. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  20226. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  20227. for (var j = 0; j <= tessellation; j++) {
  20228. var v = 1 - j / tessellation;
  20229. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  20230. var dx = Math.cos(innerAngle);
  20231. var dy = Math.sin(innerAngle);
  20232. // Create a vertex.
  20233. var normal = new BABYLON.Vector3(dx, dy, 0);
  20234. var position = normal.scale(thickness / 2);
  20235. var textureCoordinate = new BABYLON.Vector2(u, v);
  20236. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  20237. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  20238. positions.push(position.x, position.y, position.z);
  20239. normals.push(normal.x, normal.y, normal.z);
  20240. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20241. // And create indices for two triangles.
  20242. var nextI = (i + 1) % stride;
  20243. var nextJ = (j + 1) % stride;
  20244. indices.push(i * stride + j);
  20245. indices.push(i * stride + nextJ);
  20246. indices.push(nextI * stride + j);
  20247. indices.push(i * stride + nextJ);
  20248. indices.push(nextI * stride + nextJ);
  20249. indices.push(nextI * stride + j);
  20250. }
  20251. }
  20252. // Result
  20253. var vertexData = new BABYLON.VertexData();
  20254. vertexData.indices = indices;
  20255. vertexData.positions = positions;
  20256. vertexData.normals = normals;
  20257. vertexData.uvs = uvs;
  20258. return vertexData;
  20259. };
  20260. VertexData.CreateLines = function (points) {
  20261. var indices = [];
  20262. var positions = [];
  20263. for (var index = 0; index < points.length; index++) {
  20264. positions.push(points[index].x, points[index].y, points[index].z);
  20265. if (index > 0) {
  20266. indices.push(index - 1);
  20267. indices.push(index);
  20268. }
  20269. }
  20270. // Result
  20271. var vertexData = new BABYLON.VertexData();
  20272. vertexData.indices = indices;
  20273. vertexData.positions = positions;
  20274. return vertexData;
  20275. };
  20276. VertexData.CreateGround = function (width, height, subdivisions) {
  20277. var indices = [];
  20278. var positions = [];
  20279. var normals = [];
  20280. var uvs = [];
  20281. var row, col;
  20282. width = width || 1;
  20283. height = height || 1;
  20284. subdivisions = subdivisions || 1;
  20285. for (row = 0; row <= subdivisions; row++) {
  20286. for (col = 0; col <= subdivisions; col++) {
  20287. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20288. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20289. positions.push(position.x, position.y, position.z);
  20290. normals.push(normal.x, normal.y, normal.z);
  20291. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20292. }
  20293. }
  20294. for (row = 0; row < subdivisions; row++) {
  20295. for (col = 0; col < subdivisions; col++) {
  20296. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20297. indices.push(col + 1 + row * (subdivisions + 1));
  20298. indices.push(col + row * (subdivisions + 1));
  20299. indices.push(col + (row + 1) * (subdivisions + 1));
  20300. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20301. indices.push(col + row * (subdivisions + 1));
  20302. }
  20303. }
  20304. // Result
  20305. var vertexData = new BABYLON.VertexData();
  20306. vertexData.indices = indices;
  20307. vertexData.positions = positions;
  20308. vertexData.normals = normals;
  20309. vertexData.uvs = uvs;
  20310. return vertexData;
  20311. };
  20312. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  20313. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  20314. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  20315. var indices = [];
  20316. var positions = [];
  20317. var normals = [];
  20318. var uvs = [];
  20319. var row, col, tileRow, tileCol;
  20320. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  20321. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  20322. precision.w = (precision.w < 1) ? 1 : precision.w;
  20323. precision.h = (precision.h < 1) ? 1 : precision.h;
  20324. var tileSize = {
  20325. 'w': (xmax - xmin) / subdivisions.w,
  20326. 'h': (zmax - zmin) / subdivisions.h
  20327. };
  20328. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  20329. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  20330. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  20331. }
  20332. }
  20333. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  20334. // Indices
  20335. var base = positions.length / 3;
  20336. var rowLength = precision.w + 1;
  20337. for (row = 0; row < precision.h; row++) {
  20338. for (col = 0; col < precision.w; col++) {
  20339. var square = [
  20340. base + col + row * rowLength,
  20341. base + (col + 1) + row * rowLength,
  20342. base + (col + 1) + (row + 1) * rowLength,
  20343. base + col + (row + 1) * rowLength
  20344. ];
  20345. indices.push(square[1]);
  20346. indices.push(square[2]);
  20347. indices.push(square[3]);
  20348. indices.push(square[0]);
  20349. indices.push(square[1]);
  20350. indices.push(square[3]);
  20351. }
  20352. }
  20353. // Position, normals and uvs
  20354. var position = BABYLON.Vector3.Zero();
  20355. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20356. for (row = 0; row <= precision.h; row++) {
  20357. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  20358. for (col = 0; col <= precision.w; col++) {
  20359. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  20360. position.y = 0;
  20361. positions.push(position.x, position.y, position.z);
  20362. normals.push(normal.x, normal.y, normal.z);
  20363. uvs.push(col / precision.w, row / precision.h);
  20364. }
  20365. }
  20366. }
  20367. // Result
  20368. var vertexData = new BABYLON.VertexData();
  20369. vertexData.indices = indices;
  20370. vertexData.positions = positions;
  20371. vertexData.normals = normals;
  20372. vertexData.uvs = uvs;
  20373. return vertexData;
  20374. };
  20375. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  20376. var indices = [];
  20377. var positions = [];
  20378. var normals = [];
  20379. var uvs = [];
  20380. var row, col;
  20381. for (row = 0; row <= subdivisions; row++) {
  20382. for (col = 0; col <= subdivisions; col++) {
  20383. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20384. // Compute height
  20385. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  20386. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  20387. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  20388. var r = buffer[pos] / 255.0;
  20389. var g = buffer[pos + 1] / 255.0;
  20390. var b = buffer[pos + 2] / 255.0;
  20391. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20392. position.y = minHeight + (maxHeight - minHeight) * gradient;
  20393. // Add vertex
  20394. positions.push(position.x, position.y, position.z);
  20395. normals.push(0, 0, 0);
  20396. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20397. }
  20398. }
  20399. for (row = 0; row < subdivisions; row++) {
  20400. for (col = 0; col < subdivisions; col++) {
  20401. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20402. indices.push(col + 1 + row * (subdivisions + 1));
  20403. indices.push(col + row * (subdivisions + 1));
  20404. indices.push(col + (row + 1) * (subdivisions + 1));
  20405. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20406. indices.push(col + row * (subdivisions + 1));
  20407. }
  20408. }
  20409. // Normals
  20410. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20411. // Result
  20412. var vertexData = new BABYLON.VertexData();
  20413. vertexData.indices = indices;
  20414. vertexData.positions = positions;
  20415. vertexData.normals = normals;
  20416. vertexData.uvs = uvs;
  20417. return vertexData;
  20418. };
  20419. VertexData.CreatePlane = function (size) {
  20420. var indices = [];
  20421. var positions = [];
  20422. var normals = [];
  20423. var uvs = [];
  20424. size = size || 1;
  20425. // Vertices
  20426. var halfSize = size / 2.0;
  20427. positions.push(-halfSize, -halfSize, 0);
  20428. normals.push(0, 0, -1.0);
  20429. uvs.push(0.0, 0.0);
  20430. positions.push(halfSize, -halfSize, 0);
  20431. normals.push(0, 0, -1.0);
  20432. uvs.push(1.0, 0.0);
  20433. positions.push(halfSize, halfSize, 0);
  20434. normals.push(0, 0, -1.0);
  20435. uvs.push(1.0, 1.0);
  20436. positions.push(-halfSize, halfSize, 0);
  20437. normals.push(0, 0, -1.0);
  20438. uvs.push(0.0, 1.0);
  20439. // Indices
  20440. indices.push(0);
  20441. indices.push(1);
  20442. indices.push(2);
  20443. indices.push(0);
  20444. indices.push(2);
  20445. indices.push(3);
  20446. // Result
  20447. var vertexData = new BABYLON.VertexData();
  20448. vertexData.indices = indices;
  20449. vertexData.positions = positions;
  20450. vertexData.normals = normals;
  20451. vertexData.uvs = uvs;
  20452. return vertexData;
  20453. };
  20454. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20455. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  20456. var indices = [];
  20457. var positions = [];
  20458. var normals = [];
  20459. var uvs = [];
  20460. radius = radius || 2;
  20461. tube = tube || 0.5;
  20462. radialSegments = radialSegments || 32;
  20463. tubularSegments = tubularSegments || 32;
  20464. p = p || 2;
  20465. q = q || 3;
  20466. // Helper
  20467. var getPos = function (angle) {
  20468. var cu = Math.cos(angle);
  20469. var su = Math.sin(angle);
  20470. var quOverP = q / p * angle;
  20471. var cs = Math.cos(quOverP);
  20472. var tx = radius * (2 + cs) * 0.5 * cu;
  20473. var ty = radius * (2 + cs) * su * 0.5;
  20474. var tz = radius * Math.sin(quOverP) * 0.5;
  20475. return new BABYLON.Vector3(tx, ty, tz);
  20476. };
  20477. for (var i = 0; i <= radialSegments; i++) {
  20478. var modI = i % radialSegments;
  20479. var u = modI / radialSegments * 2 * p * Math.PI;
  20480. var p1 = getPos(u);
  20481. var p2 = getPos(u + 0.01);
  20482. var tang = p2.subtract(p1);
  20483. var n = p2.add(p1);
  20484. var bitan = BABYLON.Vector3.Cross(tang, n);
  20485. n = BABYLON.Vector3.Cross(bitan, tang);
  20486. bitan.normalize();
  20487. n.normalize();
  20488. for (var j = 0; j < tubularSegments; j++) {
  20489. var modJ = j % tubularSegments;
  20490. var v = modJ / tubularSegments * 2 * Math.PI;
  20491. var cx = -tube * Math.cos(v);
  20492. var cy = tube * Math.sin(v);
  20493. positions.push(p1.x + cx * n.x + cy * bitan.x);
  20494. positions.push(p1.y + cx * n.y + cy * bitan.y);
  20495. positions.push(p1.z + cx * n.z + cy * bitan.z);
  20496. uvs.push(i / radialSegments);
  20497. uvs.push(j / tubularSegments);
  20498. }
  20499. }
  20500. for (i = 0; i < radialSegments; i++) {
  20501. for (j = 0; j < tubularSegments; j++) {
  20502. var jNext = (j + 1) % tubularSegments;
  20503. var a = i * tubularSegments + j;
  20504. var b = (i + 1) * tubularSegments + j;
  20505. var c = (i + 1) * tubularSegments + jNext;
  20506. var d = i * tubularSegments + jNext;
  20507. indices.push(d);
  20508. indices.push(b);
  20509. indices.push(a);
  20510. indices.push(d);
  20511. indices.push(c);
  20512. indices.push(b);
  20513. }
  20514. }
  20515. // Normals
  20516. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20517. // Result
  20518. var vertexData = new BABYLON.VertexData();
  20519. vertexData.indices = indices;
  20520. vertexData.positions = positions;
  20521. vertexData.normals = normals;
  20522. vertexData.uvs = uvs;
  20523. return vertexData;
  20524. };
  20525. // Tools
  20526. VertexData.ComputeNormals = function (positions, indices, normals) {
  20527. var positionVectors = [];
  20528. var facesOfVertices = [];
  20529. var index;
  20530. for (index = 0; index < positions.length; index += 3) {
  20531. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  20532. positionVectors.push(vector3);
  20533. facesOfVertices.push([]);
  20534. }
  20535. // Compute normals
  20536. var facesNormals = [];
  20537. for (index = 0; index < indices.length / 3; index++) {
  20538. var i1 = indices[index * 3];
  20539. var i2 = indices[index * 3 + 1];
  20540. var i3 = indices[index * 3 + 2];
  20541. var p1 = positionVectors[i1];
  20542. var p2 = positionVectors[i2];
  20543. var p3 = positionVectors[i3];
  20544. var p1p2 = p1.subtract(p2);
  20545. var p3p2 = p3.subtract(p2);
  20546. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20547. facesOfVertices[i1].push(index);
  20548. facesOfVertices[i2].push(index);
  20549. facesOfVertices[i3].push(index);
  20550. }
  20551. for (index = 0; index < positionVectors.length; index++) {
  20552. var faces = facesOfVertices[index];
  20553. var normal = BABYLON.Vector3.Zero();
  20554. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  20555. normal.addInPlace(facesNormals[faces[faceIndex]]);
  20556. }
  20557. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  20558. normals[index * 3] = normal.x;
  20559. normals[index * 3 + 1] = normal.y;
  20560. normals[index * 3 + 2] = normal.z;
  20561. }
  20562. };
  20563. return VertexData;
  20564. })();
  20565. BABYLON.VertexData = VertexData;
  20566. })(BABYLON || (BABYLON = {}));
  20567. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  20568. var BABYLON;
  20569. (function (BABYLON) {
  20570. var buildCamera = function (that, name) {
  20571. that._leftCamera.isIntermediate = true;
  20572. that.subCameras.push(that._leftCamera);
  20573. that.subCameras.push(that._rightCamera);
  20574. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  20575. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  20576. that._anaglyphPostProcess.onApply = function (effect) {
  20577. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  20578. };
  20579. that._update();
  20580. };
  20581. var AnaglyphArcRotateCamera = (function (_super) {
  20582. __extends(AnaglyphArcRotateCamera, _super);
  20583. // ANY
  20584. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  20585. _super.call(this, name, alpha, beta, radius, target, scene);
  20586. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20587. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  20588. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  20589. buildCamera(this, name);
  20590. }
  20591. AnaglyphArcRotateCamera.prototype._update = function () {
  20592. this._updateCamera(this._leftCamera);
  20593. this._updateCamera(this._rightCamera);
  20594. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  20595. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  20596. _super.prototype._update.call(this);
  20597. };
  20598. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  20599. camera.beta = this.beta;
  20600. camera.radius = this.radius;
  20601. camera.minZ = this.minZ;
  20602. camera.maxZ = this.maxZ;
  20603. camera.fov = this.fov;
  20604. camera.target = this.target;
  20605. };
  20606. return AnaglyphArcRotateCamera;
  20607. })(BABYLON.ArcRotateCamera);
  20608. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  20609. var AnaglyphFreeCamera = (function (_super) {
  20610. __extends(AnaglyphFreeCamera, _super);
  20611. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  20612. _super.call(this, name, position, scene);
  20613. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20614. this._transformMatrix = new BABYLON.Matrix();
  20615. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  20616. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  20617. buildCamera(this, name);
  20618. }
  20619. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  20620. var target = this.getTarget();
  20621. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  20622. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  20623. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  20624. };
  20625. AnaglyphFreeCamera.prototype._update = function () {
  20626. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  20627. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  20628. this._updateCamera(this._leftCamera);
  20629. this._updateCamera(this._rightCamera);
  20630. _super.prototype._update.call(this);
  20631. };
  20632. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  20633. camera.minZ = this.minZ;
  20634. camera.maxZ = this.maxZ;
  20635. camera.fov = this.fov;
  20636. camera.viewport = this.viewport;
  20637. camera.setTarget(this.getTarget());
  20638. };
  20639. return AnaglyphFreeCamera;
  20640. })(BABYLON.FreeCamera);
  20641. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  20642. })(BABYLON || (BABYLON = {}));
  20643. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  20644. var BABYLON;
  20645. (function (BABYLON) {
  20646. var AnaglyphPostProcess = (function (_super) {
  20647. __extends(AnaglyphPostProcess, _super);
  20648. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20649. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  20650. }
  20651. return AnaglyphPostProcess;
  20652. })(BABYLON.PostProcess);
  20653. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  20654. })(BABYLON || (BABYLON = {}));
  20655. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  20656. var BABYLON;
  20657. (function (BABYLON) {
  20658. var Tags = (function () {
  20659. function Tags() {
  20660. }
  20661. Tags.EnableFor = function (obj) {
  20662. obj._tags = obj._tags || {};
  20663. obj.hasTags = function () {
  20664. return Tags.HasTags(obj);
  20665. };
  20666. obj.addTags = function (tagsString) {
  20667. return Tags.AddTagsTo(obj, tagsString);
  20668. };
  20669. obj.removeTags = function (tagsString) {
  20670. return Tags.RemoveTagsFrom(obj, tagsString);
  20671. };
  20672. obj.matchesTagsQuery = function (tagsQuery) {
  20673. return Tags.MatchesQuery(obj, tagsQuery);
  20674. };
  20675. };
  20676. Tags.DisableFor = function (obj) {
  20677. delete obj._tags;
  20678. delete obj.hasTags;
  20679. delete obj.addTags;
  20680. delete obj.removeTags;
  20681. delete obj.matchesTagsQuery;
  20682. };
  20683. Tags.HasTags = function (obj) {
  20684. if (!obj._tags) {
  20685. return false;
  20686. }
  20687. return !BABYLON.Tools.IsEmpty(obj._tags);
  20688. };
  20689. Tags.GetTags = function (obj) {
  20690. if (!obj._tags) {
  20691. return null;
  20692. }
  20693. return obj._tags;
  20694. };
  20695. // the tags 'true' and 'false' are reserved and cannot be used as tags
  20696. // a tag cannot start with '||', '&&', and '!'
  20697. // it cannot contain whitespaces
  20698. Tags.AddTagsTo = function (obj, tagsString) {
  20699. if (!tagsString) {
  20700. return;
  20701. }
  20702. var tags = tagsString.split(" ");
  20703. for (var t in tags) {
  20704. Tags._AddTagTo(obj, tags[t]);
  20705. }
  20706. };
  20707. Tags._AddTagTo = function (obj, tag) {
  20708. tag = tag.trim();
  20709. if (tag === "" || tag === "true" || tag === "false") {
  20710. return;
  20711. }
  20712. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  20713. return;
  20714. }
  20715. Tags.EnableFor(obj);
  20716. obj._tags[tag] = true;
  20717. };
  20718. Tags.RemoveTagsFrom = function (obj, tagsString) {
  20719. if (!Tags.HasTags(obj)) {
  20720. return;
  20721. }
  20722. var tags = tagsString.split(" ");
  20723. for (var t in tags) {
  20724. Tags._RemoveTagFrom(obj, tags[t]);
  20725. }
  20726. };
  20727. Tags._RemoveTagFrom = function (obj, tag) {
  20728. delete obj._tags[tag];
  20729. };
  20730. Tags.MatchesQuery = function (obj, tagsQuery) {
  20731. if (tagsQuery === undefined) {
  20732. return true;
  20733. }
  20734. if (tagsQuery === "") {
  20735. return Tags.HasTags(obj);
  20736. }
  20737. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  20738. return Tags.HasTags(obj) && obj._tags[r];
  20739. });
  20740. };
  20741. return Tags;
  20742. })();
  20743. BABYLON.Tags = Tags;
  20744. })(BABYLON || (BABYLON = {}));
  20745. //# sourceMappingURL=babylon.tags.js.map
  20746. var BABYLON;
  20747. (function (BABYLON) {
  20748. (function (Internals) {
  20749. var AndOrNotEvaluator = (function () {
  20750. function AndOrNotEvaluator() {
  20751. }
  20752. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  20753. if (!query.match(/\([^\(\)]*\)/g)) {
  20754. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  20755. } else {
  20756. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  20757. // remove parenthesis
  20758. r = r.slice(1, r.length - 1);
  20759. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  20760. });
  20761. }
  20762. if (query === "true") {
  20763. return true;
  20764. }
  20765. if (query === "false") {
  20766. return false;
  20767. }
  20768. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  20769. };
  20770. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  20771. evaluateCallback = evaluateCallback || (function (r) {
  20772. return r === "true" ? true : false;
  20773. });
  20774. var result;
  20775. var or = parenthesisContent.split("||");
  20776. for (var i in or) {
  20777. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  20778. var and = ori.split("&&");
  20779. if (and.length > 1) {
  20780. for (var j = 0; j < and.length; ++j) {
  20781. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  20782. if (andj !== "true" && andj !== "false") {
  20783. if (andj[0] === "!") {
  20784. result = !evaluateCallback(andj.substring(1));
  20785. } else {
  20786. result = evaluateCallback(andj);
  20787. }
  20788. } else {
  20789. result = andj === "true" ? true : false;
  20790. }
  20791. if (!result) {
  20792. ori = "false";
  20793. break;
  20794. }
  20795. }
  20796. }
  20797. if (result || ori === "true") {
  20798. result = true;
  20799. break;
  20800. }
  20801. // result equals false (or undefined)
  20802. if (ori !== "true" && ori !== "false") {
  20803. if (ori[0] === "!") {
  20804. result = !evaluateCallback(ori.substring(1));
  20805. } else {
  20806. result = evaluateCallback(ori);
  20807. }
  20808. } else {
  20809. result = ori === "true" ? true : false;
  20810. }
  20811. }
  20812. // the whole parenthesis scope is replaced by 'true' or 'false'
  20813. return result ? "true" : "false";
  20814. };
  20815. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  20816. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  20817. // remove whitespaces
  20818. r = r.replace(/[\s]/g, function () {
  20819. return "";
  20820. });
  20821. return r.length % 2 ? "!" : "";
  20822. });
  20823. booleanString = booleanString.trim();
  20824. if (booleanString === "!true") {
  20825. booleanString = "false";
  20826. } else if (booleanString === "!false") {
  20827. booleanString = "true";
  20828. }
  20829. return booleanString;
  20830. };
  20831. return AndOrNotEvaluator;
  20832. })();
  20833. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  20834. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20835. var Internals = BABYLON.Internals;
  20836. })(BABYLON || (BABYLON = {}));
  20837. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  20838. var BABYLON;
  20839. (function (BABYLON) {
  20840. var PostProcessRenderPass = (function () {
  20841. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  20842. this._enabled = true;
  20843. this._refCount = 0;
  20844. this._name = name;
  20845. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  20846. this.setRenderList(renderList);
  20847. this._renderTexture.onBeforeRender = beforeRender;
  20848. this._renderTexture.onAfterRender = afterRender;
  20849. this._scene = scene;
  20850. this._renderList = renderList;
  20851. }
  20852. // private
  20853. PostProcessRenderPass.prototype._incRefCount = function () {
  20854. if (this._refCount === 0) {
  20855. this._scene.customRenderTargets.push(this._renderTexture);
  20856. }
  20857. return ++this._refCount;
  20858. };
  20859. PostProcessRenderPass.prototype._decRefCount = function () {
  20860. this._refCount--;
  20861. if (this._refCount <= 0) {
  20862. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  20863. }
  20864. return this._refCount;
  20865. };
  20866. PostProcessRenderPass.prototype._update = function () {
  20867. this.setRenderList(this._renderList);
  20868. };
  20869. // public
  20870. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  20871. this._renderTexture.renderList = renderList;
  20872. };
  20873. PostProcessRenderPass.prototype.getRenderTexture = function () {
  20874. return this._renderTexture;
  20875. };
  20876. return PostProcessRenderPass;
  20877. })();
  20878. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  20879. })(BABYLON || (BABYLON = {}));
  20880. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  20881. var BABYLON;
  20882. (function (BABYLON) {
  20883. var PostProcessRenderEffect = (function () {
  20884. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  20885. this._engine = engine;
  20886. this._name = name;
  20887. this._singleInstance = singleInstance || true;
  20888. this._getPostProcess = getPostProcess;
  20889. this._cameras = [];
  20890. this._indicesForCamera = [];
  20891. this._postProcesses = {};
  20892. this._renderPasses = {};
  20893. this._renderEffectAsPasses = {};
  20894. }
  20895. PostProcessRenderEffect.prototype._update = function () {
  20896. for (var renderPassName in this._renderPasses) {
  20897. this._renderPasses[renderPassName]._update();
  20898. }
  20899. };
  20900. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  20901. this._renderPasses[renderPass._name] = renderPass;
  20902. this._linkParameters();
  20903. };
  20904. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  20905. delete this._renderPasses[renderPass._name];
  20906. this._linkParameters();
  20907. };
  20908. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  20909. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  20910. this._linkParameters();
  20911. };
  20912. PostProcessRenderEffect.prototype.getPass = function (passName) {
  20913. for (var renderPassName in this._renderPasses) {
  20914. if (renderPassName === passName) {
  20915. return this._renderPasses[passName];
  20916. }
  20917. }
  20918. };
  20919. PostProcessRenderEffect.prototype.emptyPasses = function () {
  20920. this._renderPasses = {};
  20921. this._linkParameters();
  20922. };
  20923. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  20924. var cameraKey;
  20925. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20926. for (var i = 0; i < _cam.length; i++) {
  20927. var camera = _cam[i];
  20928. var cameraName = camera.name;
  20929. if (this._singleInstance) {
  20930. cameraKey = 0;
  20931. } else {
  20932. cameraKey = cameraName;
  20933. }
  20934. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  20935. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  20936. if (!this._indicesForCamera[cameraName]) {
  20937. this._indicesForCamera[cameraName] = [];
  20938. }
  20939. this._indicesForCamera[cameraName].push(index);
  20940. if (this._cameras.indexOf(camera) === -1) {
  20941. this._cameras[cameraName] = camera;
  20942. }
  20943. for (var passName in this._renderPasses) {
  20944. this._renderPasses[passName]._incRefCount();
  20945. }
  20946. }
  20947. this._linkParameters();
  20948. };
  20949. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  20950. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20951. for (var i = 0; i < _cam.length; i++) {
  20952. var camera = _cam[i];
  20953. var cameraName = camera.name;
  20954. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20955. var index = this._cameras.indexOf(cameraName);
  20956. this._indicesForCamera.splice(index, 1);
  20957. this._cameras.splice(index, 1);
  20958. for (var passName in this._renderPasses) {
  20959. this._renderPasses[passName]._decRefCount();
  20960. }
  20961. }
  20962. };
  20963. PostProcessRenderEffect.prototype._enable = function (cameras) {
  20964. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20965. for (var i = 0; i < _cam.length; i++) {
  20966. var camera = _cam[i];
  20967. var cameraName = camera.name;
  20968. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  20969. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  20970. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  20971. }
  20972. }
  20973. for (var passName in this._renderPasses) {
  20974. this._renderPasses[passName]._incRefCount();
  20975. }
  20976. }
  20977. };
  20978. PostProcessRenderEffect.prototype._disable = function (cameras) {
  20979. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20980. for (var i = 0; i < _cam.length; i++) {
  20981. var camera = _cam[i];
  20982. var cameraName = camera.Name;
  20983. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20984. for (var passName in this._renderPasses) {
  20985. this._renderPasses[passName]._decRefCount();
  20986. }
  20987. }
  20988. };
  20989. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  20990. if (this._singleInstance) {
  20991. return this._postProcesses[0];
  20992. } else {
  20993. return this._postProcesses[camera.name];
  20994. }
  20995. };
  20996. PostProcessRenderEffect.prototype._linkParameters = function () {
  20997. var _this = this;
  20998. for (var index in this._postProcesses) {
  20999. if (this.applyParameters) {
  21000. this.applyParameters(this._postProcesses[index]);
  21001. }
  21002. this._postProcesses[index].onBeforeRender = function (effect) {
  21003. _this._linkTextures(effect);
  21004. };
  21005. }
  21006. };
  21007. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  21008. for (var renderPassName in this._renderPasses) {
  21009. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  21010. }
  21011. for (var renderEffectName in this._renderEffectAsPasses) {
  21012. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  21013. }
  21014. };
  21015. return PostProcessRenderEffect;
  21016. })();
  21017. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  21018. })(BABYLON || (BABYLON = {}));
  21019. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  21020. var BABYLON;
  21021. (function (BABYLON) {
  21022. var PostProcessRenderPipeline = (function () {
  21023. function PostProcessRenderPipeline(engine, name) {
  21024. this._engine = engine;
  21025. this._name = name;
  21026. this._renderEffects = {};
  21027. this._renderEffectsForIsolatedPass = {};
  21028. this._cameras = [];
  21029. }
  21030. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  21031. this._renderEffects[renderEffect._name] = renderEffect;
  21032. };
  21033. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  21034. var renderEffects = this._renderEffects[renderEffectName];
  21035. if (!renderEffects) {
  21036. return;
  21037. }
  21038. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21039. };
  21040. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  21041. var renderEffects = this._renderEffects[renderEffectName];
  21042. if (!renderEffects) {
  21043. return;
  21044. }
  21045. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21046. };
  21047. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  21048. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21049. var indicesToDelete = [];
  21050. for (var i = 0; i < _cam.length; i++) {
  21051. var camera = _cam[i];
  21052. var cameraName = camera.name;
  21053. if (this._cameras.indexOf(camera) === -1) {
  21054. this._cameras[cameraName] = camera;
  21055. } else if (unique) {
  21056. indicesToDelete.push(i);
  21057. }
  21058. }
  21059. for (var i = 0; i < indicesToDelete.length; i++) {
  21060. cameras.splice(indicesToDelete[i], 1);
  21061. }
  21062. for (var renderEffectName in this._renderEffects) {
  21063. this._renderEffects[renderEffectName]._attachCameras(_cam);
  21064. }
  21065. };
  21066. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  21067. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21068. for (var renderEffectName in this._renderEffects) {
  21069. this._renderEffects[renderEffectName]._detachCameras(_cam);
  21070. }
  21071. for (var i = 0; i < _cam.length; i++) {
  21072. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  21073. }
  21074. };
  21075. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  21076. var _this = this;
  21077. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21078. var pass = null;
  21079. for (var renderEffectName in this._renderEffects) {
  21080. pass = this._renderEffects[renderEffectName].getPass(passName);
  21081. if (pass != null) {
  21082. break;
  21083. }
  21084. }
  21085. if (pass === null) {
  21086. return;
  21087. }
  21088. for (var renderEffectName in this._renderEffects) {
  21089. this._renderEffects[renderEffectName]._disable(_cam);
  21090. }
  21091. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  21092. for (var i = 0; i < _cam.length; i++) {
  21093. var camera = _cam[i];
  21094. var cameraName = camera.name;
  21095. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21096. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21097. });
  21098. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  21099. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  21100. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  21101. }
  21102. };
  21103. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  21104. var _this = this;
  21105. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21106. for (var i = 0; i < _cam.length; i++) {
  21107. var camera = _cam[i];
  21108. var cameraName = camera.name;
  21109. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21110. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21111. });
  21112. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  21113. }
  21114. for (var renderEffectName in this._renderEffects) {
  21115. this._renderEffects[renderEffectName]._enable(_cam);
  21116. }
  21117. };
  21118. PostProcessRenderPipeline.prototype._update = function () {
  21119. for (var renderEffectName in this._renderEffects) {
  21120. this._renderEffects[renderEffectName]._update();
  21121. }
  21122. for (var i = 0; i < this._cameras.length; i++) {
  21123. var cameraName = this._cameras[i].name;
  21124. if (this._renderEffectsForIsolatedPass[cameraName]) {
  21125. this._renderEffectsForIsolatedPass[cameraName]._update();
  21126. }
  21127. }
  21128. };
  21129. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  21130. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  21131. return PostProcessRenderPipeline;
  21132. })();
  21133. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  21134. })(BABYLON || (BABYLON = {}));
  21135. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  21136. var BABYLON;
  21137. (function (BABYLON) {
  21138. var PostProcessRenderPipelineManager = (function () {
  21139. function PostProcessRenderPipelineManager() {
  21140. this._renderPipelines = {};
  21141. }
  21142. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  21143. this._renderPipelines[renderPipeline._name] = renderPipeline;
  21144. };
  21145. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  21146. var renderPipeline = this._renderPipelines[renderPipelineName];
  21147. if (!renderPipeline) {
  21148. return;
  21149. }
  21150. renderPipeline._attachCameras(cameras, unique);
  21151. };
  21152. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  21153. var renderPipeline = this._renderPipelines[renderPipelineName];
  21154. if (!renderPipeline) {
  21155. return;
  21156. }
  21157. renderPipeline._detachCameras(cameras);
  21158. };
  21159. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21160. var renderPipeline = this._renderPipelines[renderPipelineName];
  21161. if (!renderPipeline) {
  21162. return;
  21163. }
  21164. renderPipeline._enableEffect(renderEffectName, cameras);
  21165. };
  21166. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21167. var renderPipeline = this._renderPipelines[renderPipelineName];
  21168. if (!renderPipeline) {
  21169. return;
  21170. }
  21171. renderPipeline._disableEffect(renderEffectName, cameras);
  21172. };
  21173. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  21174. var renderPipeline = this._renderPipelines[renderPipelineName];
  21175. if (!renderPipeline) {
  21176. return;
  21177. }
  21178. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  21179. };
  21180. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  21181. var renderPipeline = this._renderPipelines[renderPipelineName];
  21182. if (!renderPipeline) {
  21183. return;
  21184. }
  21185. renderPipeline._disableDisplayOnlyPass(cameras);
  21186. };
  21187. PostProcessRenderPipelineManager.prototype.update = function () {
  21188. for (var renderPipelineName in this._renderPipelines) {
  21189. this._renderPipelines[renderPipelineName]._update();
  21190. }
  21191. };
  21192. return PostProcessRenderPipelineManager;
  21193. })();
  21194. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  21195. })(BABYLON || (BABYLON = {}));
  21196. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  21197. var BABYLON;
  21198. (function (BABYLON) {
  21199. var DisplayPassPostProcess = (function (_super) {
  21200. __extends(DisplayPassPostProcess, _super);
  21201. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21202. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  21203. }
  21204. return DisplayPassPostProcess;
  21205. })(BABYLON.PostProcess);
  21206. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  21207. })(BABYLON || (BABYLON = {}));
  21208. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  21209. var BABYLON;
  21210. (function (BABYLON) {
  21211. var BoundingBoxRenderer = (function () {
  21212. function BoundingBoxRenderer(scene) {
  21213. this.frontColor = new BABYLON.Color3(1, 1, 1);
  21214. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  21215. this.showBackLines = true;
  21216. this.renderList = new BABYLON.SmartArray(32);
  21217. this._scene = scene;
  21218. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21219. attributes: ["position"],
  21220. uniforms: ["worldViewProjection", "color"]
  21221. });
  21222. var engine = this._scene.getEngine();
  21223. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  21224. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  21225. 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]);
  21226. }
  21227. BoundingBoxRenderer.prototype.reset = function () {
  21228. this.renderList.reset();
  21229. };
  21230. BoundingBoxRenderer.prototype.render = function () {
  21231. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  21232. return;
  21233. }
  21234. var engine = this._scene.getEngine();
  21235. engine.setDepthWrite(false);
  21236. this._colorShader._preBind();
  21237. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  21238. var boundingBox = this.renderList.data[boundingBoxIndex];
  21239. var min = boundingBox.minimum;
  21240. var max = boundingBox.maximum;
  21241. var diff = max.subtract(min);
  21242. var median = min.add(diff.scale(0.5));
  21243. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  21244. // VBOs
  21245. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  21246. if (this.showBackLines) {
  21247. // Back
  21248. engine.setDepthFunctionToGreaterOrEqual();
  21249. this._scene.resetCachedMaterial();
  21250. this._colorShader.setColor4("color", this.backColor.toColor4());
  21251. this._colorShader.bind(worldMatrix);
  21252. // Draw order
  21253. engine.draw(false, 0, 24);
  21254. }
  21255. // Front
  21256. engine.setDepthFunctionToLess();
  21257. this._scene.resetCachedMaterial();
  21258. this._colorShader.setColor4("color", this.frontColor.toColor4());
  21259. this._colorShader.bind(worldMatrix);
  21260. // Draw order
  21261. engine.draw(false, 0, 24);
  21262. }
  21263. this._colorShader.unbind();
  21264. engine.setDepthFunctionToLessOrEqual();
  21265. engine.setDepthWrite(true);
  21266. };
  21267. BoundingBoxRenderer.prototype.dispose = function () {
  21268. this._colorShader.dispose();
  21269. this._vb.dispose();
  21270. this._scene.getEngine()._releaseBuffer(this._ib);
  21271. };
  21272. return BoundingBoxRenderer;
  21273. })();
  21274. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  21275. })(BABYLON || (BABYLON = {}));
  21276. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  21277. var BABYLON;
  21278. (function (BABYLON) {
  21279. (function (Internals) {
  21280. /*
  21281. * Based on jsTGALoader - Javascript loader for TGA file
  21282. * By Vincent Thibault
  21283. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  21284. */
  21285. var TGATools = (function () {
  21286. function TGATools() {
  21287. }
  21288. TGATools.GetTGAHeader = function (data) {
  21289. var offset = 0;
  21290. var header = {
  21291. id_length: data[offset++],
  21292. colormap_type: data[offset++],
  21293. image_type: data[offset++],
  21294. colormap_index: data[offset++] | data[offset++] << 8,
  21295. colormap_length: data[offset++] | data[offset++] << 8,
  21296. colormap_size: data[offset++],
  21297. origin: [
  21298. data[offset++] | data[offset++] << 8,
  21299. data[offset++] | data[offset++] << 8
  21300. ],
  21301. width: data[offset++] | data[offset++] << 8,
  21302. height: data[offset++] | data[offset++] << 8,
  21303. pixel_size: data[offset++],
  21304. flags: data[offset++]
  21305. };
  21306. return header;
  21307. };
  21308. TGATools.UploadContent = function (gl, data) {
  21309. // Not enough data to contain header ?
  21310. if (data.length < 19) {
  21311. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  21312. return;
  21313. }
  21314. // Read Header
  21315. var offset = 18;
  21316. var header = TGATools.GetTGAHeader(data);
  21317. // Assume it's a valid Targa file.
  21318. if (header.id_length + offset > data.length) {
  21319. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  21320. return;
  21321. }
  21322. // Skip not needed data
  21323. offset += header.id_length;
  21324. var use_rle = false;
  21325. var use_pal = false;
  21326. var use_rgb = false;
  21327. var use_grey = false;
  21328. switch (header.image_type) {
  21329. case TGATools._TYPE_RLE_INDEXED:
  21330. use_rle = true;
  21331. case TGATools._TYPE_INDEXED:
  21332. use_pal = true;
  21333. break;
  21334. case TGATools._TYPE_RLE_RGB:
  21335. use_rle = true;
  21336. case TGATools._TYPE_RGB:
  21337. use_rgb = true;
  21338. break;
  21339. case TGATools._TYPE_RLE_GREY:
  21340. use_rle = true;
  21341. case TGATools._TYPE_GREY:
  21342. use_grey = true;
  21343. break;
  21344. }
  21345. var pixel_data;
  21346. var numAlphaBits = header.flags & 0xf;
  21347. var pixel_size = header.pixel_size >> 3;
  21348. var pixel_total = header.width * header.height * pixel_size;
  21349. // Read palettes
  21350. var palettes;
  21351. if (use_pal) {
  21352. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  21353. }
  21354. // Read LRE
  21355. if (use_rle) {
  21356. pixel_data = new Uint8Array(pixel_total);
  21357. var c, count, i;
  21358. var localOffset = 0;
  21359. var pixels = new Uint8Array(pixel_size);
  21360. while (offset < pixel_total && localOffset < pixel_total) {
  21361. c = data[offset++];
  21362. count = (c & 0x7f) + 1;
  21363. // RLE pixels
  21364. if (c & 0x80) {
  21365. for (i = 0; i < pixel_size; ++i) {
  21366. pixels[i] = data[offset++];
  21367. }
  21368. for (i = 0; i < count; ++i) {
  21369. pixel_data.set(pixels, localOffset + i * pixel_size);
  21370. }
  21371. localOffset += pixel_size * count;
  21372. } else {
  21373. count *= pixel_size;
  21374. for (i = 0; i < count; ++i) {
  21375. pixel_data[localOffset + i] = data[offset++];
  21376. }
  21377. localOffset += count;
  21378. }
  21379. }
  21380. } else {
  21381. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  21382. }
  21383. // Load to texture
  21384. var x_start, y_start, x_step, y_step, y_end, x_end;
  21385. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  21386. default:
  21387. case TGATools._ORIGIN_UL:
  21388. x_start = 0;
  21389. x_step = 1;
  21390. x_end = header.width;
  21391. y_start = 0;
  21392. y_step = 1;
  21393. y_end = header.height;
  21394. break;
  21395. case TGATools._ORIGIN_BL:
  21396. x_start = 0;
  21397. x_step = 1;
  21398. x_end = header.width;
  21399. y_start = header.height - 1;
  21400. y_step = -1;
  21401. y_end = -1;
  21402. break;
  21403. case TGATools._ORIGIN_UR:
  21404. x_start = header.width - 1;
  21405. x_step = -1;
  21406. x_end = -1;
  21407. y_start = 0;
  21408. y_step = 1;
  21409. y_end = header.height;
  21410. break;
  21411. case TGATools._ORIGIN_BR:
  21412. x_start = header.width - 1;
  21413. x_step = -1;
  21414. x_end = -1;
  21415. y_start = header.height - 1;
  21416. y_step = -1;
  21417. y_end = -1;
  21418. break;
  21419. }
  21420. // Load the specify method
  21421. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  21422. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  21423. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  21424. };
  21425. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21426. var image = pixel_data, colormap = palettes;
  21427. var width = header.width, height = header.height;
  21428. var color, i = 0, x, y;
  21429. var imageData = new Uint8Array(width * height * 4);
  21430. for (y = y_start; y !== y_end; y += y_step) {
  21431. for (x = x_start; x !== x_end; x += x_step, i++) {
  21432. color = image[i];
  21433. imageData[(x + width * y) * 4 + 3] = 255;
  21434. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  21435. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  21436. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  21437. }
  21438. }
  21439. return imageData;
  21440. };
  21441. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21442. var image = pixel_data;
  21443. var width = header.width, height = header.height;
  21444. var color, i = 0, x, y;
  21445. var imageData = new Uint8Array(width * height * 4);
  21446. for (y = y_start; y !== y_end; y += y_step) {
  21447. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21448. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  21449. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  21450. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  21451. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  21452. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  21453. }
  21454. }
  21455. return imageData;
  21456. };
  21457. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21458. var image = pixel_data;
  21459. var width = header.width, height = header.height;
  21460. var i = 0, x, y;
  21461. var imageData = new Uint8Array(width * height * 4);
  21462. for (y = y_start; y !== y_end; y += y_step) {
  21463. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  21464. imageData[(x + width * y) * 4 + 3] = 255;
  21465. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21466. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21467. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21468. }
  21469. }
  21470. return imageData;
  21471. };
  21472. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21473. var image = pixel_data;
  21474. var width = header.width, height = header.height;
  21475. var i = 0, x, y;
  21476. var imageData = new Uint8Array(width * height * 4);
  21477. for (y = y_start; y !== y_end; y += y_step) {
  21478. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  21479. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21480. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21481. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21482. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  21483. }
  21484. }
  21485. return imageData;
  21486. };
  21487. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21488. var image = pixel_data;
  21489. var width = header.width, height = header.height;
  21490. var color, i = 0, x, y;
  21491. var imageData = new Uint8Array(width * height * 4);
  21492. for (y = y_start; y !== y_end; y += y_step) {
  21493. for (x = x_start; x !== x_end; x += x_step, i++) {
  21494. color = image[i];
  21495. imageData[(x + width * y) * 4 + 0] = color;
  21496. imageData[(x + width * y) * 4 + 1] = color;
  21497. imageData[(x + width * y) * 4 + 2] = color;
  21498. imageData[(x + width * y) * 4 + 3] = 255;
  21499. }
  21500. }
  21501. return imageData;
  21502. };
  21503. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21504. var image = pixel_data;
  21505. var width = header.width, height = header.height;
  21506. var i = 0, x, y;
  21507. var imageData = new Uint8Array(width * height * 4);
  21508. for (y = y_start; y !== y_end; y += y_step) {
  21509. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21510. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  21511. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  21512. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21513. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  21514. }
  21515. }
  21516. return imageData;
  21517. };
  21518. TGATools._TYPE_NO_DATA = 0;
  21519. TGATools._TYPE_INDEXED = 1;
  21520. TGATools._TYPE_RGB = 2;
  21521. TGATools._TYPE_GREY = 3;
  21522. TGATools._TYPE_RLE_INDEXED = 9;
  21523. TGATools._TYPE_RLE_RGB = 10;
  21524. TGATools._TYPE_RLE_GREY = 11;
  21525. TGATools._ORIGIN_MASK = 0x30;
  21526. TGATools._ORIGIN_SHIFT = 0x04;
  21527. TGATools._ORIGIN_BL = 0x00;
  21528. TGATools._ORIGIN_BR = 0x01;
  21529. TGATools._ORIGIN_UL = 0x02;
  21530. TGATools._ORIGIN_UR = 0x03;
  21531. return TGATools;
  21532. })();
  21533. Internals.TGATools = TGATools;
  21534. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21535. var Internals = BABYLON.Internals;
  21536. })(BABYLON || (BABYLON = {}));
  21537. //# sourceMappingURL=babylon.tools.tga.js.map
  21538. var BABYLON;
  21539. (function (BABYLON) {
  21540. (function (Internals) {
  21541. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  21542. // All values and structures referenced from:
  21543. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  21544. var DDS_MAGIC = 0x20534444;
  21545. 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;
  21546. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  21547. 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;
  21548. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  21549. function FourCCToInt32(value) {
  21550. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  21551. }
  21552. function Int32ToFourCC(value) {
  21553. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  21554. }
  21555. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  21556. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  21557. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  21558. var headerLengthInt = 31;
  21559. // Offsets into the header array
  21560. var off_magic = 0;
  21561. var off_size = 1;
  21562. var off_flags = 2;
  21563. var off_height = 3;
  21564. var off_width = 4;
  21565. var off_mipmapCount = 7;
  21566. var off_pfFlags = 20;
  21567. var off_pfFourCC = 21;
  21568. var off_RGBbpp = 22;
  21569. var off_RMask = 23;
  21570. var off_GMask = 24;
  21571. var off_BMask = 25;
  21572. var off_AMask = 26;
  21573. var off_caps1 = 27;
  21574. var off_caps2 = 28;
  21575. ;
  21576. var DDSTools = (function () {
  21577. function DDSTools() {
  21578. }
  21579. DDSTools.GetDDSInfo = function (arrayBuffer) {
  21580. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  21581. var mipmapCount = 1;
  21582. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  21583. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21584. }
  21585. return {
  21586. width: header[off_width],
  21587. height: header[off_height],
  21588. mipmapCount: mipmapCount,
  21589. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  21590. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  21591. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  21592. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  21593. };
  21594. };
  21595. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21596. var byteArray = new Uint8Array(dataLength);
  21597. var srcData = new Uint8Array(arrayBuffer);
  21598. var index = 0;
  21599. for (var y = height - 1; y >= 0; y--) {
  21600. for (var x = 0; x < width; x++) {
  21601. var srcPos = dataOffset + (x + y * width) * 4;
  21602. byteArray[index + 2] = srcData[srcPos];
  21603. byteArray[index + 1] = srcData[srcPos + 1];
  21604. byteArray[index] = srcData[srcPos + 2];
  21605. byteArray[index + 3] = srcData[srcPos + 3];
  21606. index += 4;
  21607. }
  21608. }
  21609. return byteArray;
  21610. };
  21611. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21612. var byteArray = new Uint8Array(dataLength);
  21613. var srcData = new Uint8Array(arrayBuffer);
  21614. var index = 0;
  21615. for (var y = height - 1; y >= 0; y--) {
  21616. for (var x = 0; x < width; x++) {
  21617. var srcPos = dataOffset + (x + y * width) * 3;
  21618. byteArray[index + 2] = srcData[srcPos];
  21619. byteArray[index + 1] = srcData[srcPos + 1];
  21620. byteArray[index] = srcData[srcPos + 2];
  21621. index += 3;
  21622. }
  21623. }
  21624. return byteArray;
  21625. };
  21626. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21627. var byteArray = new Uint8Array(dataLength);
  21628. var srcData = new Uint8Array(arrayBuffer);
  21629. var index = 0;
  21630. for (var y = height - 1; y >= 0; y--) {
  21631. for (var x = 0; x < width; x++) {
  21632. var srcPos = dataOffset + (x + y * width);
  21633. byteArray[index] = srcData[srcPos];
  21634. index++;
  21635. }
  21636. }
  21637. return byteArray;
  21638. };
  21639. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  21640. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  21641. if (header[off_magic] != DDS_MAGIC) {
  21642. BABYLON.Tools.Error("Invalid magic number in DDS header");
  21643. return;
  21644. }
  21645. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  21646. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  21647. return;
  21648. }
  21649. if (info.isFourCC) {
  21650. fourCC = header[off_pfFourCC];
  21651. switch (fourCC) {
  21652. case FOURCC_DXT1:
  21653. blockBytes = 8;
  21654. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21655. break;
  21656. case FOURCC_DXT3:
  21657. blockBytes = 16;
  21658. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21659. break;
  21660. case FOURCC_DXT5:
  21661. blockBytes = 16;
  21662. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21663. break;
  21664. default:
  21665. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  21666. return;
  21667. }
  21668. }
  21669. mipmapCount = 1;
  21670. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  21671. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21672. }
  21673. var bpp = header[off_RGBbpp];
  21674. for (var face = 0; face < faces; face++) {
  21675. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  21676. width = header[off_width];
  21677. height = header[off_height];
  21678. dataOffset = header[off_size] + 4;
  21679. for (i = 0; i < mipmapCount; ++i) {
  21680. if (info.isRGB) {
  21681. if (bpp == 24) {
  21682. dataLength = width * height * 3;
  21683. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21684. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  21685. } else {
  21686. dataLength = width * height * 4;
  21687. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21688. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  21689. }
  21690. } else if (info.isLuminance) {
  21691. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  21692. var unpaddedRowSize = width;
  21693. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  21694. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  21695. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21696. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  21697. } else {
  21698. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  21699. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  21700. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  21701. }
  21702. dataOffset += dataLength;
  21703. width *= 0.5;
  21704. height *= 0.5;
  21705. width = Math.max(1.0, width);
  21706. height = Math.max(1.0, height);
  21707. }
  21708. }
  21709. };
  21710. return DDSTools;
  21711. })();
  21712. Internals.DDSTools = DDSTools;
  21713. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21714. var Internals = BABYLON.Internals;
  21715. })(BABYLON || (BABYLON = {}));
  21716. //# sourceMappingURL=babylon.tools.dds.js.map
  21717. var BABYLON;
  21718. (function (BABYLON) {
  21719. var SmartArray = (function () {
  21720. function SmartArray(capacity) {
  21721. this.length = 0;
  21722. this._duplicateId = 0;
  21723. this.data = new Array(capacity);
  21724. this._id = SmartArray._GlobalId++;
  21725. }
  21726. SmartArray.prototype.push = function (value) {
  21727. this.data[this.length++] = value;
  21728. if (this.length > this.data.length) {
  21729. this.data.length *= 2;
  21730. }
  21731. if (!value.__smartArrayFlags) {
  21732. value.__smartArrayFlags = {};
  21733. }
  21734. value.__smartArrayFlags[this._id] = this._duplicateId;
  21735. };
  21736. SmartArray.prototype.pushNoDuplicate = function (value) {
  21737. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  21738. return;
  21739. }
  21740. this.push(value);
  21741. };
  21742. SmartArray.prototype.sort = function (compareFn) {
  21743. this.data.sort(compareFn);
  21744. };
  21745. SmartArray.prototype.reset = function () {
  21746. this.length = 0;
  21747. this._duplicateId++;
  21748. };
  21749. SmartArray.prototype.concat = function (array) {
  21750. if (array.length === 0) {
  21751. return;
  21752. }
  21753. if (this.length + array.length > this.data.length) {
  21754. this.data.length = (this.length + array.length) * 2;
  21755. }
  21756. for (var index = 0; index < array.length; index++) {
  21757. this.data[this.length++] = (array.data || array)[index];
  21758. }
  21759. };
  21760. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  21761. if (array.length === 0) {
  21762. return;
  21763. }
  21764. if (this.length + array.length > this.data.length) {
  21765. this.data.length = (this.length + array.length) * 2;
  21766. }
  21767. for (var index = 0; index < array.length; index++) {
  21768. var item = (array.data || array)[index];
  21769. this.pushNoDuplicate(item);
  21770. }
  21771. };
  21772. SmartArray.prototype.indexOf = function (value) {
  21773. var position = this.data.indexOf(value);
  21774. if (position >= this.length) {
  21775. return -1;
  21776. }
  21777. return position;
  21778. };
  21779. SmartArray._GlobalId = 0;
  21780. return SmartArray;
  21781. })();
  21782. BABYLON.SmartArray = SmartArray;
  21783. })(BABYLON || (BABYLON = {}));
  21784. //# sourceMappingURL=babylon.smartArray.js.map
  21785. var BABYLON;
  21786. (function (BABYLON) {
  21787. var CannonJSPlugin = (function () {
  21788. function CannonJSPlugin() {
  21789. this._registeredMeshes = [];
  21790. this._physicsMaterials = [];
  21791. this.updateBodyPosition = function (mesh) {
  21792. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21793. var registeredMesh = this._registeredMeshes[index];
  21794. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21795. var body = registeredMesh.body;
  21796. var center = mesh.getBoundingInfo().boundingBox.center;
  21797. body.position.set(center.x, center.z, center.y);
  21798. body.quaternion.x = mesh.rotationQuaternion.x;
  21799. body.quaternion.z = mesh.rotationQuaternion.y;
  21800. body.quaternion.y = mesh.rotationQuaternion.z;
  21801. body.quaternion.w = -mesh.rotationQuaternion.w;
  21802. return;
  21803. }
  21804. }
  21805. };
  21806. }
  21807. CannonJSPlugin.prototype.initialize = function (iterations) {
  21808. if (typeof iterations === "undefined") { iterations = 10; }
  21809. this._world = new CANNON.World();
  21810. this._world.broadphase = new CANNON.NaiveBroadphase();
  21811. this._world.solver.iterations = iterations;
  21812. };
  21813. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21814. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21815. };
  21816. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21817. this._world.step(delta);
  21818. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21819. var registeredMesh = this._registeredMeshes[index];
  21820. if (registeredMesh.isChild) {
  21821. continue;
  21822. }
  21823. // Body position
  21824. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21825. var deltaPos = registeredMesh.delta;
  21826. if (deltaPos) {
  21827. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21828. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21829. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21830. } else {
  21831. registeredMesh.mesh.position.x = bodyX;
  21832. registeredMesh.mesh.position.y = bodyZ;
  21833. registeredMesh.mesh.position.z = bodyY;
  21834. }
  21835. if (!registeredMesh.mesh.rotationQuaternion) {
  21836. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21837. }
  21838. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21839. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21840. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21841. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21842. }
  21843. };
  21844. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21845. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21846. };
  21847. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21848. this.unregisterMesh(mesh);
  21849. mesh.computeWorldMatrix(true);
  21850. switch (impostor) {
  21851. case BABYLON.PhysicsEngine.SphereImpostor:
  21852. var bbox = mesh.getBoundingInfo().boundingBox;
  21853. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21854. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21855. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21856. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21857. case BABYLON.PhysicsEngine.BoxImpostor:
  21858. bbox = mesh.getBoundingInfo().boundingBox;
  21859. var min = bbox.minimumWorld;
  21860. var max = bbox.maximumWorld;
  21861. var box = max.subtract(min).scale(0.5);
  21862. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21863. case BABYLON.PhysicsEngine.PlaneImpostor:
  21864. return this._createPlane(mesh, options);
  21865. case BABYLON.PhysicsEngine.MeshImpostor:
  21866. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21867. var rawFaces = mesh.getIndices();
  21868. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21869. }
  21870. return null;
  21871. };
  21872. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21873. var shape = new CANNON.Sphere(radius);
  21874. if (!options) {
  21875. return shape;
  21876. }
  21877. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21878. };
  21879. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21880. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21881. if (!options) {
  21882. return shape;
  21883. }
  21884. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21885. };
  21886. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21887. var shape = new CANNON.Plane();
  21888. if (!options) {
  21889. return shape;
  21890. }
  21891. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21892. };
  21893. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21894. var verts = [], faces = [];
  21895. mesh.computeWorldMatrix(true);
  21896. for (var i = 0; i < rawVerts.length; i += 3) {
  21897. var transformed = BABYLON.Vector3.Zero();
  21898. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21899. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21900. }
  21901. for (var j = 0; j < rawFaces.length; j += 3) {
  21902. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21903. }
  21904. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21905. if (!options) {
  21906. return shape;
  21907. }
  21908. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21909. };
  21910. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21911. var index;
  21912. var mat;
  21913. for (index = 0; index < this._physicsMaterials.length; index++) {
  21914. mat = this._physicsMaterials[index];
  21915. if (mat.friction === friction && mat.restitution === restitution) {
  21916. return mat;
  21917. }
  21918. }
  21919. var currentMat = new CANNON.Material();
  21920. currentMat.friction = friction;
  21921. currentMat.restitution = restitution;
  21922. this._physicsMaterials.push(currentMat);
  21923. for (index = 0; index < this._physicsMaterials.length; index++) {
  21924. mat = this._physicsMaterials[index];
  21925. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21926. contactMaterial.contactEquationStiffness = 1e10;
  21927. contactMaterial.contactEquationRegularizationTime = 10;
  21928. this._world.addContactMaterial(contactMaterial);
  21929. }
  21930. return currentMat;
  21931. };
  21932. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21933. var initialRotation = null;
  21934. if (mesh.rotationQuaternion) {
  21935. initialRotation = mesh.rotationQuaternion.clone();
  21936. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21937. }
  21938. // The delta between the mesh position and the mesh bounding box center
  21939. var bbox = mesh.getBoundingInfo().boundingBox;
  21940. var deltaPosition = mesh.position.subtract(bbox.center);
  21941. var material = this._addMaterial(friction, restitution);
  21942. var body = new CANNON.RigidBody(mass, shape, material);
  21943. if (initialRotation) {
  21944. body.quaternion.x = initialRotation.x;
  21945. body.quaternion.z = initialRotation.y;
  21946. body.quaternion.y = initialRotation.z;
  21947. body.quaternion.w = -initialRotation.w;
  21948. }
  21949. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21950. this._world.add(body);
  21951. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21952. return body;
  21953. };
  21954. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21955. var compoundShape = new CANNON.Compound();
  21956. for (var index = 0; index < parts.length; index++) {
  21957. var mesh = parts[index].mesh;
  21958. var shape = this.registerMesh(mesh, parts[index].impostor);
  21959. if (index == 0) {
  21960. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21961. } else {
  21962. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21963. }
  21964. }
  21965. var initialMesh = parts[0].mesh;
  21966. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21967. body.parts = parts;
  21968. return body;
  21969. };
  21970. CannonJSPlugin.prototype._unbindBody = function (body) {
  21971. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21972. var registeredMesh = this._registeredMeshes[index];
  21973. if (registeredMesh.body === body) {
  21974. registeredMesh.body = null;
  21975. registeredMesh.delta = 0;
  21976. }
  21977. }
  21978. };
  21979. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21980. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21981. var registeredMesh = this._registeredMeshes[index];
  21982. if (registeredMesh.mesh === mesh) {
  21983. // Remove body
  21984. if (registeredMesh.body) {
  21985. this._world.remove(registeredMesh.body);
  21986. this._unbindBody(registeredMesh.body);
  21987. }
  21988. this._registeredMeshes.splice(index, 1);
  21989. return;
  21990. }
  21991. }
  21992. };
  21993. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21994. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21995. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21996. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21997. var registeredMesh = this._registeredMeshes[index];
  21998. if (registeredMesh.mesh === mesh) {
  21999. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22000. return;
  22001. }
  22002. }
  22003. };
  22004. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22005. var body1 = null, body2 = null;
  22006. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22007. var registeredMesh = this._registeredMeshes[index];
  22008. if (registeredMesh.mesh === mesh1) {
  22009. body1 = registeredMesh.body;
  22010. } else if (registeredMesh.mesh === mesh2) {
  22011. body2 = registeredMesh.body;
  22012. }
  22013. }
  22014. if (!body1 || !body2) {
  22015. return false;
  22016. }
  22017. 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));
  22018. this._world.addConstraint(constraint);
  22019. return true;
  22020. };
  22021. CannonJSPlugin.prototype.dispose = function () {
  22022. while (this._registeredMeshes.length) {
  22023. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22024. }
  22025. };
  22026. CannonJSPlugin.prototype.isSupported = function () {
  22027. return window.CANNON !== undefined;
  22028. };
  22029. return CannonJSPlugin;
  22030. })();
  22031. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22032. })(BABYLON || (BABYLON = {}));
  22033. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22034. var BABYLON;
  22035. (function (BABYLON) {
  22036. var Condition = (function () {
  22037. function Condition(actionManager) {
  22038. this._actionManager = actionManager;
  22039. }
  22040. Condition.prototype.isValid = function () {
  22041. return true;
  22042. };
  22043. Condition.prototype._getProperty = function (propertyPath) {
  22044. return this._actionManager._getProperty(propertyPath);
  22045. };
  22046. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  22047. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22048. };
  22049. return Condition;
  22050. })();
  22051. BABYLON.Condition = Condition;
  22052. var ValueCondition = (function (_super) {
  22053. __extends(ValueCondition, _super);
  22054. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  22055. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  22056. _super.call(this, actionManager);
  22057. this.propertyPath = propertyPath;
  22058. this.value = value;
  22059. this.operator = operator;
  22060. this._target = this._getEffectiveTarget(target, this.propertyPath);
  22061. this._property = this._getProperty(this.propertyPath);
  22062. }
  22063. Object.defineProperty(ValueCondition, "IsEqual", {
  22064. get: function () {
  22065. return ValueCondition._IsEqual;
  22066. },
  22067. enumerable: true,
  22068. configurable: true
  22069. });
  22070. Object.defineProperty(ValueCondition, "IsDifferent", {
  22071. get: function () {
  22072. return ValueCondition._IsDifferent;
  22073. },
  22074. enumerable: true,
  22075. configurable: true
  22076. });
  22077. Object.defineProperty(ValueCondition, "IsGreater", {
  22078. get: function () {
  22079. return ValueCondition._IsGreater;
  22080. },
  22081. enumerable: true,
  22082. configurable: true
  22083. });
  22084. Object.defineProperty(ValueCondition, "IsLesser", {
  22085. get: function () {
  22086. return ValueCondition._IsLesser;
  22087. },
  22088. enumerable: true,
  22089. configurable: true
  22090. });
  22091. // Methods
  22092. ValueCondition.prototype.isValid = function () {
  22093. switch (this.operator) {
  22094. case ValueCondition.IsGreater:
  22095. return this._target[this._property] > this.value;
  22096. case ValueCondition.IsLesser:
  22097. return this._target[this._property] < this.value;
  22098. case ValueCondition.IsEqual:
  22099. case ValueCondition.IsDifferent:
  22100. var check;
  22101. if (this.value.equals) {
  22102. check = this.value.equals(this._target[this._property]);
  22103. } else {
  22104. check = this.value === this._target[this._property];
  22105. }
  22106. return this.operator === ValueCondition.IsEqual ? check : !check;
  22107. }
  22108. return false;
  22109. };
  22110. ValueCondition._IsEqual = 0;
  22111. ValueCondition._IsDifferent = 1;
  22112. ValueCondition._IsGreater = 2;
  22113. ValueCondition._IsLesser = 3;
  22114. return ValueCondition;
  22115. })(Condition);
  22116. BABYLON.ValueCondition = ValueCondition;
  22117. var PredicateCondition = (function (_super) {
  22118. __extends(PredicateCondition, _super);
  22119. function PredicateCondition(actionManager, predicate) {
  22120. _super.call(this, actionManager);
  22121. this.predicate = predicate;
  22122. }
  22123. PredicateCondition.prototype.isValid = function () {
  22124. return this.predicate();
  22125. };
  22126. return PredicateCondition;
  22127. })(Condition);
  22128. BABYLON.PredicateCondition = PredicateCondition;
  22129. var StateCondition = (function (_super) {
  22130. __extends(StateCondition, _super);
  22131. function StateCondition(actionManager, target, value) {
  22132. _super.call(this, actionManager);
  22133. this.value = value;
  22134. this._target = target;
  22135. }
  22136. // Methods
  22137. StateCondition.prototype.isValid = function () {
  22138. return this._target.state === this.value;
  22139. };
  22140. return StateCondition;
  22141. })(Condition);
  22142. BABYLON.StateCondition = StateCondition;
  22143. })(BABYLON || (BABYLON = {}));
  22144. //# sourceMappingURL=babylon.condition.js.map
  22145. var BABYLON;
  22146. (function (BABYLON) {
  22147. var Action = (function () {
  22148. function Action(triggerOptions, condition) {
  22149. this.triggerOptions = triggerOptions;
  22150. if (triggerOptions.parameter) {
  22151. this.trigger = triggerOptions.trigger;
  22152. this._triggerParameter = triggerOptions.parameter;
  22153. } else {
  22154. this.trigger = triggerOptions;
  22155. }
  22156. this._nextActiveAction = this;
  22157. this._condition = condition;
  22158. }
  22159. // Methods
  22160. Action.prototype._prepare = function () {
  22161. };
  22162. Action.prototype.getTriggerParameter = function () {
  22163. return this._triggerParameter;
  22164. };
  22165. Action.prototype._executeCurrent = function (evt) {
  22166. if (this._condition) {
  22167. var currentRenderId = this._actionManager.getScene().getRenderId();
  22168. // We cache the current evaluation for the current frame
  22169. if (this._condition._evaluationId === currentRenderId) {
  22170. if (!this._condition._currentResult) {
  22171. return;
  22172. }
  22173. } else {
  22174. this._condition._evaluationId = currentRenderId;
  22175. if (!this._condition.isValid()) {
  22176. this._condition._currentResult = false;
  22177. return;
  22178. }
  22179. this._condition._currentResult = true;
  22180. }
  22181. }
  22182. this._nextActiveAction.execute(evt);
  22183. if (this._nextActiveAction._child) {
  22184. if (!this._nextActiveAction._child._actionManager) {
  22185. this._nextActiveAction._child._actionManager = this._actionManager;
  22186. }
  22187. this._nextActiveAction = this._nextActiveAction._child;
  22188. } else {
  22189. this._nextActiveAction = this;
  22190. }
  22191. };
  22192. Action.prototype.execute = function (evt) {
  22193. };
  22194. Action.prototype.then = function (action) {
  22195. this._child = action;
  22196. action._actionManager = this._actionManager;
  22197. action._prepare();
  22198. return action;
  22199. };
  22200. Action.prototype._getProperty = function (propertyPath) {
  22201. return this._actionManager._getProperty(propertyPath);
  22202. };
  22203. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  22204. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22205. };
  22206. return Action;
  22207. })();
  22208. BABYLON.Action = Action;
  22209. })(BABYLON || (BABYLON = {}));
  22210. //# sourceMappingURL=babylon.action.js.map
  22211. var BABYLON;
  22212. (function (BABYLON) {
  22213. var ActionEvent = (function () {
  22214. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  22215. this.source = source;
  22216. this.pointerX = pointerX;
  22217. this.pointerY = pointerY;
  22218. this.meshUnderPointer = meshUnderPointer;
  22219. this.sourceEvent = sourceEvent;
  22220. }
  22221. ActionEvent.CreateNew = function (source, evt) {
  22222. var scene = source.getScene();
  22223. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22224. };
  22225. ActionEvent.CreateNewFromScene = function (scene, evt) {
  22226. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22227. };
  22228. return ActionEvent;
  22229. })();
  22230. BABYLON.ActionEvent = ActionEvent;
  22231. var ActionManager = (function () {
  22232. function ActionManager(scene) {
  22233. // Members
  22234. this.actions = new Array();
  22235. this._scene = scene;
  22236. scene._actionManagers.push(this);
  22237. }
  22238. Object.defineProperty(ActionManager, "NothingTrigger", {
  22239. get: function () {
  22240. return ActionManager._NothingTrigger;
  22241. },
  22242. enumerable: true,
  22243. configurable: true
  22244. });
  22245. Object.defineProperty(ActionManager, "OnPickTrigger", {
  22246. get: function () {
  22247. return ActionManager._OnPickTrigger;
  22248. },
  22249. enumerable: true,
  22250. configurable: true
  22251. });
  22252. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  22253. get: function () {
  22254. return ActionManager._OnLeftPickTrigger;
  22255. },
  22256. enumerable: true,
  22257. configurable: true
  22258. });
  22259. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  22260. get: function () {
  22261. return ActionManager._OnRightPickTrigger;
  22262. },
  22263. enumerable: true,
  22264. configurable: true
  22265. });
  22266. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  22267. get: function () {
  22268. return ActionManager._OnCenterPickTrigger;
  22269. },
  22270. enumerable: true,
  22271. configurable: true
  22272. });
  22273. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  22274. get: function () {
  22275. return ActionManager._OnPointerOverTrigger;
  22276. },
  22277. enumerable: true,
  22278. configurable: true
  22279. });
  22280. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  22281. get: function () {
  22282. return ActionManager._OnPointerOutTrigger;
  22283. },
  22284. enumerable: true,
  22285. configurable: true
  22286. });
  22287. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  22288. get: function () {
  22289. return ActionManager._OnEveryFrameTrigger;
  22290. },
  22291. enumerable: true,
  22292. configurable: true
  22293. });
  22294. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  22295. get: function () {
  22296. return ActionManager._OnIntersectionEnterTrigger;
  22297. },
  22298. enumerable: true,
  22299. configurable: true
  22300. });
  22301. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  22302. get: function () {
  22303. return ActionManager._OnIntersectionExitTrigger;
  22304. },
  22305. enumerable: true,
  22306. configurable: true
  22307. });
  22308. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  22309. get: function () {
  22310. return ActionManager._OnKeyDownTrigger;
  22311. },
  22312. enumerable: true,
  22313. configurable: true
  22314. });
  22315. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  22316. get: function () {
  22317. return ActionManager._OnKeyUpTrigger;
  22318. },
  22319. enumerable: true,
  22320. configurable: true
  22321. });
  22322. // Methods
  22323. ActionManager.prototype.dispose = function () {
  22324. var index = this._scene._actionManagers.indexOf(this);
  22325. if (index > -1) {
  22326. this._scene._actionManagers.splice(index, 1);
  22327. }
  22328. };
  22329. ActionManager.prototype.getScene = function () {
  22330. return this._scene;
  22331. };
  22332. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  22333. for (var index = 0; index < this.actions.length; index++) {
  22334. var action = this.actions[index];
  22335. if (triggers.indexOf(action.trigger) > -1) {
  22336. return true;
  22337. }
  22338. }
  22339. return false;
  22340. };
  22341. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  22342. get: function () {
  22343. for (var index = 0; index < this.actions.length; index++) {
  22344. var action = this.actions[index];
  22345. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  22346. return true;
  22347. }
  22348. }
  22349. return false;
  22350. },
  22351. enumerable: true,
  22352. configurable: true
  22353. });
  22354. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  22355. get: function () {
  22356. for (var index = 0; index < this.actions.length; index++) {
  22357. var action = this.actions[index];
  22358. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  22359. return true;
  22360. }
  22361. }
  22362. return false;
  22363. },
  22364. enumerable: true,
  22365. configurable: true
  22366. });
  22367. ActionManager.prototype.registerAction = function (action) {
  22368. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  22369. if (this.getScene().actionManager !== this) {
  22370. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  22371. return null;
  22372. }
  22373. }
  22374. this.actions.push(action);
  22375. action._actionManager = this;
  22376. action._prepare();
  22377. return action;
  22378. };
  22379. ActionManager.prototype.processTrigger = function (trigger, evt) {
  22380. for (var index = 0; index < this.actions.length; index++) {
  22381. var action = this.actions[index];
  22382. if (action.trigger === trigger) {
  22383. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  22384. var parameter = action.getTriggerParameter();
  22385. if (parameter) {
  22386. if (evt.sourceEvent.key !== parameter) {
  22387. continue;
  22388. }
  22389. }
  22390. }
  22391. action._executeCurrent(evt);
  22392. }
  22393. }
  22394. };
  22395. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  22396. var properties = propertyPath.split(".");
  22397. for (var index = 0; index < properties.length - 1; index++) {
  22398. target = target[properties[index]];
  22399. }
  22400. return target;
  22401. };
  22402. ActionManager.prototype._getProperty = function (propertyPath) {
  22403. var properties = propertyPath.split(".");
  22404. return properties[properties.length - 1];
  22405. };
  22406. ActionManager._NothingTrigger = 0;
  22407. ActionManager._OnPickTrigger = 1;
  22408. ActionManager._OnLeftPickTrigger = 2;
  22409. ActionManager._OnRightPickTrigger = 3;
  22410. ActionManager._OnCenterPickTrigger = 4;
  22411. ActionManager._OnPointerOverTrigger = 5;
  22412. ActionManager._OnPointerOutTrigger = 6;
  22413. ActionManager._OnEveryFrameTrigger = 7;
  22414. ActionManager._OnIntersectionEnterTrigger = 8;
  22415. ActionManager._OnIntersectionExitTrigger = 9;
  22416. ActionManager._OnKeyDownTrigger = 10;
  22417. ActionManager._OnKeyUpTrigger = 11;
  22418. return ActionManager;
  22419. })();
  22420. BABYLON.ActionManager = ActionManager;
  22421. })(BABYLON || (BABYLON = {}));
  22422. //# sourceMappingURL=babylon.actionManager.js.map
  22423. var BABYLON;
  22424. (function (BABYLON) {
  22425. var InterpolateValueAction = (function (_super) {
  22426. __extends(InterpolateValueAction, _super);
  22427. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  22428. if (typeof duration === "undefined") { duration = 1000; }
  22429. _super.call(this, triggerOptions, condition);
  22430. this.propertyPath = propertyPath;
  22431. this.value = value;
  22432. this.duration = duration;
  22433. this.stopOtherAnimations = stopOtherAnimations;
  22434. this._target = target;
  22435. }
  22436. InterpolateValueAction.prototype._prepare = function () {
  22437. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22438. this._property = this._getProperty(this.propertyPath);
  22439. };
  22440. InterpolateValueAction.prototype.execute = function () {
  22441. var scene = this._actionManager.getScene();
  22442. var keys = [
  22443. {
  22444. frame: 0,
  22445. value: this._target[this._property]
  22446. }, {
  22447. frame: 100,
  22448. value: this.value
  22449. }
  22450. ];
  22451. var dataType;
  22452. if (typeof this.value === "number") {
  22453. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  22454. } else if (this.value instanceof BABYLON.Color3) {
  22455. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  22456. } else if (this.value instanceof BABYLON.Vector3) {
  22457. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  22458. } else if (this.value instanceof BABYLON.Matrix) {
  22459. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  22460. } else if (this.value instanceof BABYLON.Quaternion) {
  22461. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  22462. } else {
  22463. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  22464. return;
  22465. }
  22466. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  22467. animation.setKeys(keys);
  22468. if (this.stopOtherAnimations) {
  22469. scene.stopAnimation(this._target);
  22470. }
  22471. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  22472. };
  22473. return InterpolateValueAction;
  22474. })(BABYLON.Action);
  22475. BABYLON.InterpolateValueAction = InterpolateValueAction;
  22476. })(BABYLON || (BABYLON = {}));
  22477. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  22478. var BABYLON;
  22479. (function (BABYLON) {
  22480. var SwitchBooleanAction = (function (_super) {
  22481. __extends(SwitchBooleanAction, _super);
  22482. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  22483. _super.call(this, triggerOptions, condition);
  22484. this.propertyPath = propertyPath;
  22485. this._target = target;
  22486. }
  22487. SwitchBooleanAction.prototype._prepare = function () {
  22488. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22489. this._property = this._getProperty(this.propertyPath);
  22490. };
  22491. SwitchBooleanAction.prototype.execute = function () {
  22492. this._target[this._property] = !this._target[this._property];
  22493. };
  22494. return SwitchBooleanAction;
  22495. })(BABYLON.Action);
  22496. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  22497. var SetStateAction = (function (_super) {
  22498. __extends(SetStateAction, _super);
  22499. function SetStateAction(triggerOptions, target, value, condition) {
  22500. _super.call(this, triggerOptions, condition);
  22501. this.value = value;
  22502. this._target = target;
  22503. }
  22504. SetStateAction.prototype.execute = function () {
  22505. this._target.state = this.value;
  22506. };
  22507. return SetStateAction;
  22508. })(BABYLON.Action);
  22509. BABYLON.SetStateAction = SetStateAction;
  22510. var SetValueAction = (function (_super) {
  22511. __extends(SetValueAction, _super);
  22512. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  22513. _super.call(this, triggerOptions, condition);
  22514. this.propertyPath = propertyPath;
  22515. this.value = value;
  22516. this._target = target;
  22517. }
  22518. SetValueAction.prototype._prepare = function () {
  22519. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22520. this._property = this._getProperty(this.propertyPath);
  22521. };
  22522. SetValueAction.prototype.execute = function () {
  22523. this._target[this._property] = this.value;
  22524. };
  22525. return SetValueAction;
  22526. })(BABYLON.Action);
  22527. BABYLON.SetValueAction = SetValueAction;
  22528. var IncrementValueAction = (function (_super) {
  22529. __extends(IncrementValueAction, _super);
  22530. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  22531. _super.call(this, triggerOptions, condition);
  22532. this.propertyPath = propertyPath;
  22533. this.value = value;
  22534. this._target = target;
  22535. }
  22536. IncrementValueAction.prototype._prepare = function () {
  22537. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22538. this._property = this._getProperty(this.propertyPath);
  22539. if (typeof this._target[this._property] !== "number") {
  22540. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  22541. }
  22542. };
  22543. IncrementValueAction.prototype.execute = function () {
  22544. this._target[this._property] += this.value;
  22545. };
  22546. return IncrementValueAction;
  22547. })(BABYLON.Action);
  22548. BABYLON.IncrementValueAction = IncrementValueAction;
  22549. var PlayAnimationAction = (function (_super) {
  22550. __extends(PlayAnimationAction, _super);
  22551. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  22552. _super.call(this, triggerOptions, condition);
  22553. this.from = from;
  22554. this.to = to;
  22555. this.loop = loop;
  22556. this._target = target;
  22557. }
  22558. PlayAnimationAction.prototype._prepare = function () {
  22559. };
  22560. PlayAnimationAction.prototype.execute = function () {
  22561. var scene = this._actionManager.getScene();
  22562. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  22563. };
  22564. return PlayAnimationAction;
  22565. })(BABYLON.Action);
  22566. BABYLON.PlayAnimationAction = PlayAnimationAction;
  22567. var StopAnimationAction = (function (_super) {
  22568. __extends(StopAnimationAction, _super);
  22569. function StopAnimationAction(triggerOptions, target, condition) {
  22570. _super.call(this, triggerOptions, condition);
  22571. this._target = target;
  22572. }
  22573. StopAnimationAction.prototype._prepare = function () {
  22574. };
  22575. StopAnimationAction.prototype.execute = function () {
  22576. var scene = this._actionManager.getScene();
  22577. scene.stopAnimation(this._target);
  22578. };
  22579. return StopAnimationAction;
  22580. })(BABYLON.Action);
  22581. BABYLON.StopAnimationAction = StopAnimationAction;
  22582. var DoNothingAction = (function (_super) {
  22583. __extends(DoNothingAction, _super);
  22584. function DoNothingAction(triggerOptions, condition) {
  22585. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  22586. _super.call(this, triggerOptions, condition);
  22587. }
  22588. DoNothingAction.prototype.execute = function () {
  22589. };
  22590. return DoNothingAction;
  22591. })(BABYLON.Action);
  22592. BABYLON.DoNothingAction = DoNothingAction;
  22593. var CombineAction = (function (_super) {
  22594. __extends(CombineAction, _super);
  22595. function CombineAction(triggerOptions, children, condition) {
  22596. _super.call(this, triggerOptions, condition);
  22597. this.children = children;
  22598. }
  22599. CombineAction.prototype._prepare = function () {
  22600. for (var index = 0; index < this.children.length; index++) {
  22601. this.children[index]._actionManager = this._actionManager;
  22602. this.children[index]._prepare();
  22603. }
  22604. };
  22605. CombineAction.prototype.execute = function (evt) {
  22606. for (var index = 0; index < this.children.length; index++) {
  22607. this.children[index].execute(evt);
  22608. }
  22609. };
  22610. return CombineAction;
  22611. })(BABYLON.Action);
  22612. BABYLON.CombineAction = CombineAction;
  22613. var ExecuteCodeAction = (function (_super) {
  22614. __extends(ExecuteCodeAction, _super);
  22615. function ExecuteCodeAction(triggerOptions, func, condition) {
  22616. _super.call(this, triggerOptions, condition);
  22617. this.func = func;
  22618. }
  22619. ExecuteCodeAction.prototype.execute = function (evt) {
  22620. this.func(evt);
  22621. };
  22622. return ExecuteCodeAction;
  22623. })(BABYLON.Action);
  22624. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  22625. var SetParentAction = (function (_super) {
  22626. __extends(SetParentAction, _super);
  22627. function SetParentAction(triggerOptions, target, parent, condition) {
  22628. _super.call(this, triggerOptions, condition);
  22629. this._target = target;
  22630. this._parent = parent;
  22631. }
  22632. SetParentAction.prototype._prepare = function () {
  22633. };
  22634. SetParentAction.prototype.execute = function () {
  22635. if (this._target.parent === this._parent) {
  22636. return;
  22637. }
  22638. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  22639. invertParentWorldMatrix.invert();
  22640. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  22641. this._target.parent = this._parent;
  22642. };
  22643. return SetParentAction;
  22644. })(BABYLON.Action);
  22645. BABYLON.SetParentAction = SetParentAction;
  22646. })(BABYLON || (BABYLON = {}));
  22647. //# sourceMappingURL=babylon.directActions.js.map
  22648. var BABYLON;
  22649. (function (BABYLON) {
  22650. var Geometry = (function () {
  22651. function Geometry(id, scene, vertexData, updatable, mesh) {
  22652. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22653. this._totalVertices = 0;
  22654. this._indices = [];
  22655. this.id = id;
  22656. this._engine = scene.getEngine();
  22657. this._meshes = [];
  22658. this._scene = scene;
  22659. // vertexData
  22660. if (vertexData) {
  22661. this.setAllVerticesData(vertexData, updatable);
  22662. } else {
  22663. this._totalVertices = 0;
  22664. this._indices = [];
  22665. }
  22666. // applyToMesh
  22667. if (mesh) {
  22668. this.applyToMesh(mesh);
  22669. }
  22670. }
  22671. Geometry.prototype.getScene = function () {
  22672. return this._scene;
  22673. };
  22674. Geometry.prototype.getEngine = function () {
  22675. return this._engine;
  22676. };
  22677. Geometry.prototype.isReady = function () {
  22678. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  22679. };
  22680. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  22681. vertexData.applyToGeometry(this, updatable);
  22682. };
  22683. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22684. this._vertexBuffers = this._vertexBuffers || {};
  22685. if (this._vertexBuffers[kind]) {
  22686. this._vertexBuffers[kind].dispose();
  22687. }
  22688. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  22689. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22690. stride = this._vertexBuffers[kind].getStrideSize();
  22691. this._totalVertices = data.length / stride;
  22692. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22693. var meshes = this._meshes;
  22694. var numOfMeshes = meshes.length;
  22695. for (var index = 0; index < numOfMeshes; index++) {
  22696. var mesh = meshes[index];
  22697. mesh._resetPointsArrayCache();
  22698. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22699. mesh._createGlobalSubMesh();
  22700. mesh.computeWorldMatrix(true);
  22701. }
  22702. }
  22703. };
  22704. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  22705. var vertexBuffer = this.getVertexBuffer(kind);
  22706. if (!vertexBuffer) {
  22707. return;
  22708. }
  22709. vertexBuffer.updateDirectly(data, offset);
  22710. };
  22711. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  22712. var vertexBuffer = this.getVertexBuffer(kind);
  22713. if (!vertexBuffer) {
  22714. return;
  22715. }
  22716. vertexBuffer.update(data);
  22717. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22718. var extend;
  22719. var stride = vertexBuffer.getStrideSize();
  22720. this._totalVertices = data.length / stride;
  22721. if (updateExtends) {
  22722. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22723. }
  22724. var meshes = this._meshes;
  22725. var numOfMeshes = meshes.length;
  22726. for (var index = 0; index < numOfMeshes; index++) {
  22727. var mesh = meshes[index];
  22728. mesh._resetPointsArrayCache();
  22729. if (updateExtends) {
  22730. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22731. }
  22732. }
  22733. }
  22734. };
  22735. Geometry.prototype.getTotalVertices = function () {
  22736. if (!this.isReady()) {
  22737. return 0;
  22738. }
  22739. return this._totalVertices;
  22740. };
  22741. Geometry.prototype.getVerticesData = function (kind) {
  22742. var vertexBuffer = this.getVertexBuffer(kind);
  22743. if (!vertexBuffer) {
  22744. return null;
  22745. }
  22746. return vertexBuffer.getData();
  22747. };
  22748. Geometry.prototype.getVertexBuffer = function (kind) {
  22749. if (!this.isReady()) {
  22750. return null;
  22751. }
  22752. return this._vertexBuffers[kind];
  22753. };
  22754. Geometry.prototype.getVertexBuffers = function () {
  22755. if (!this.isReady()) {
  22756. return null;
  22757. }
  22758. return this._vertexBuffers;
  22759. };
  22760. Geometry.prototype.isVerticesDataPresent = function (kind) {
  22761. if (!this._vertexBuffers) {
  22762. if (this._delayInfo) {
  22763. return this._delayInfo.indexOf(kind) !== -1;
  22764. }
  22765. return false;
  22766. }
  22767. return this._vertexBuffers[kind] !== undefined;
  22768. };
  22769. Geometry.prototype.getVerticesDataKinds = function () {
  22770. var result = [];
  22771. if (!this._vertexBuffers && this._delayInfo) {
  22772. for (var kind in this._delayInfo) {
  22773. result.push(kind);
  22774. }
  22775. } else {
  22776. for (kind in this._vertexBuffers) {
  22777. result.push(kind);
  22778. }
  22779. }
  22780. return result;
  22781. };
  22782. Geometry.prototype.setIndices = function (indices, totalVertices) {
  22783. if (this._indexBuffer) {
  22784. this._engine._releaseBuffer(this._indexBuffer);
  22785. }
  22786. this._indices = indices;
  22787. if (this._meshes.length !== 0 && this._indices) {
  22788. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22789. }
  22790. if (totalVertices !== undefined) {
  22791. this._totalVertices = totalVertices;
  22792. }
  22793. var meshes = this._meshes;
  22794. var numOfMeshes = meshes.length;
  22795. for (var index = 0; index < numOfMeshes; index++) {
  22796. meshes[index]._createGlobalSubMesh();
  22797. }
  22798. };
  22799. Geometry.prototype.getTotalIndices = function () {
  22800. if (!this.isReady()) {
  22801. return 0;
  22802. }
  22803. return this._indices.length;
  22804. };
  22805. Geometry.prototype.getIndices = function () {
  22806. if (!this.isReady()) {
  22807. return null;
  22808. }
  22809. return this._indices;
  22810. };
  22811. Geometry.prototype.getIndexBuffer = function () {
  22812. if (!this.isReady()) {
  22813. return null;
  22814. }
  22815. return this._indexBuffer;
  22816. };
  22817. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  22818. var meshes = this._meshes;
  22819. var index = meshes.indexOf(mesh);
  22820. if (index === -1) {
  22821. return;
  22822. }
  22823. for (var kind in this._vertexBuffers) {
  22824. this._vertexBuffers[kind].dispose();
  22825. }
  22826. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  22827. this._indexBuffer = null;
  22828. }
  22829. meshes.splice(index, 1);
  22830. mesh._geometry = null;
  22831. if (meshes.length === 0 && shouldDispose) {
  22832. this.dispose();
  22833. }
  22834. };
  22835. Geometry.prototype.applyToMesh = function (mesh) {
  22836. if (mesh._geometry === this) {
  22837. return;
  22838. }
  22839. var previousGeometry = mesh._geometry;
  22840. if (previousGeometry) {
  22841. previousGeometry.releaseForMesh(mesh);
  22842. }
  22843. var meshes = this._meshes;
  22844. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  22845. mesh._geometry = this;
  22846. this._scene.pushGeometry(this);
  22847. meshes.push(mesh);
  22848. if (this.isReady()) {
  22849. this._applyToMesh(mesh);
  22850. } else {
  22851. mesh._boundingInfo = this._boundingInfo;
  22852. }
  22853. };
  22854. Geometry.prototype._applyToMesh = function (mesh) {
  22855. var numOfMeshes = this._meshes.length;
  22856. for (var kind in this._vertexBuffers) {
  22857. if (numOfMeshes === 1) {
  22858. this._vertexBuffers[kind].create();
  22859. }
  22860. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  22861. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22862. mesh._resetPointsArrayCache();
  22863. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  22864. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22865. mesh._createGlobalSubMesh();
  22866. //bounding info was just created again, world matrix should be applied again.
  22867. mesh._updateBoundingInfo();
  22868. }
  22869. }
  22870. // indexBuffer
  22871. if (numOfMeshes === 1 && this._indices) {
  22872. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22873. }
  22874. if (this._indexBuffer) {
  22875. this._indexBuffer.references = numOfMeshes;
  22876. }
  22877. };
  22878. Geometry.prototype.load = function (scene, onLoaded) {
  22879. var _this = this;
  22880. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22881. return;
  22882. }
  22883. if (this.isReady()) {
  22884. if (onLoaded) {
  22885. onLoaded();
  22886. }
  22887. return;
  22888. }
  22889. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22890. scene._addPendingData(this);
  22891. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22892. _this._delayLoadingFunction(JSON.parse(data), _this);
  22893. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22894. _this._delayInfo = [];
  22895. scene._removePendingData(_this);
  22896. var meshes = _this._meshes;
  22897. var numOfMeshes = meshes.length;
  22898. for (var index = 0; index < numOfMeshes; index++) {
  22899. _this._applyToMesh(meshes[index]);
  22900. }
  22901. if (onLoaded) {
  22902. onLoaded();
  22903. }
  22904. }, function () {
  22905. }, scene.database);
  22906. };
  22907. Geometry.prototype.dispose = function () {
  22908. var meshes = this._meshes;
  22909. var numOfMeshes = meshes.length;
  22910. var index;
  22911. for (index = 0; index < numOfMeshes; index++) {
  22912. this.releaseForMesh(meshes[index]);
  22913. }
  22914. this._meshes = [];
  22915. for (var kind in this._vertexBuffers) {
  22916. this._vertexBuffers[kind].dispose();
  22917. }
  22918. this._vertexBuffers = [];
  22919. this._totalVertices = 0;
  22920. if (this._indexBuffer) {
  22921. this._engine._releaseBuffer(this._indexBuffer);
  22922. }
  22923. this._indexBuffer = null;
  22924. this._indices = [];
  22925. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22926. this.delayLoadingFile = null;
  22927. this._delayLoadingFunction = null;
  22928. this._delayInfo = [];
  22929. this._boundingInfo = null; // todo: .dispose()
  22930. var geometries = this._scene.getGeometries();
  22931. index = geometries.indexOf(this);
  22932. if (index > -1) {
  22933. geometries.splice(index, 1);
  22934. }
  22935. };
  22936. Geometry.prototype.copy = function (id) {
  22937. var vertexData = new BABYLON.VertexData();
  22938. vertexData.indices = [];
  22939. var indices = this.getIndices();
  22940. for (var index = 0; index < indices.length; index++) {
  22941. vertexData.indices.push(indices[index]);
  22942. }
  22943. var updatable = false;
  22944. var stopChecking = false;
  22945. for (var kind in this._vertexBuffers) {
  22946. vertexData.set(this.getVerticesData(kind), kind);
  22947. if (!stopChecking) {
  22948. updatable = this.getVertexBuffer(kind).isUpdatable();
  22949. stopChecking = !updatable;
  22950. }
  22951. }
  22952. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  22953. geometry.delayLoadState = this.delayLoadState;
  22954. geometry.delayLoadingFile = this.delayLoadingFile;
  22955. geometry._delayLoadingFunction = this._delayLoadingFunction;
  22956. for (kind in this._delayInfo) {
  22957. geometry._delayInfo = geometry._delayInfo || [];
  22958. geometry._delayInfo.push(kind);
  22959. }
  22960. // Bounding info
  22961. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  22962. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22963. return geometry;
  22964. };
  22965. // Statics
  22966. Geometry.ExtractFromMesh = function (mesh, id) {
  22967. var geometry = mesh._geometry;
  22968. if (!geometry) {
  22969. return null;
  22970. }
  22971. return geometry.copy(id);
  22972. };
  22973. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  22974. // be aware Math.random() could cause collisions
  22975. Geometry.RandomId = function () {
  22976. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  22977. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  22978. return v.toString(16);
  22979. });
  22980. };
  22981. return Geometry;
  22982. })();
  22983. BABYLON.Geometry = Geometry;
  22984. (function (Geometry) {
  22985. /////// Primitives //////////////////////////////////////////////
  22986. (function (Primitives) {
  22987. /// Abstract class
  22988. var _Primitive = (function (_super) {
  22989. __extends(_Primitive, _super);
  22990. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  22991. this._beingRegenerated = true;
  22992. this._canBeRegenerated = canBeRegenerated;
  22993. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  22994. this._beingRegenerated = false;
  22995. }
  22996. _Primitive.prototype.canBeRegenerated = function () {
  22997. return this._canBeRegenerated;
  22998. };
  22999. _Primitive.prototype.regenerate = function () {
  23000. if (!this._canBeRegenerated) {
  23001. return;
  23002. }
  23003. this._beingRegenerated = true;
  23004. this.setAllVerticesData(this._regenerateVertexData(), false);
  23005. this._beingRegenerated = false;
  23006. };
  23007. _Primitive.prototype.asNewGeometry = function (id) {
  23008. return _super.prototype.copy.call(this, id);
  23009. };
  23010. // overrides
  23011. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  23012. if (!this._beingRegenerated) {
  23013. return;
  23014. }
  23015. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  23016. };
  23017. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  23018. if (!this._beingRegenerated) {
  23019. return;
  23020. }
  23021. _super.prototype.setVerticesData.call(this, kind, data, false);
  23022. };
  23023. // to override
  23024. // protected
  23025. _Primitive.prototype._regenerateVertexData = function () {
  23026. throw new Error("Abstract method");
  23027. };
  23028. _Primitive.prototype.copy = function (id) {
  23029. throw new Error("Must be overriden in sub-classes.");
  23030. };
  23031. return _Primitive;
  23032. })(Geometry);
  23033. Primitives._Primitive = _Primitive;
  23034. var Box = (function (_super) {
  23035. __extends(Box, _super);
  23036. function Box(id, scene, size, canBeRegenerated, mesh) {
  23037. this.size = size;
  23038. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23039. }
  23040. Box.prototype._regenerateVertexData = function () {
  23041. return BABYLON.VertexData.CreateBox(this.size);
  23042. };
  23043. Box.prototype.copy = function (id) {
  23044. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23045. };
  23046. return Box;
  23047. })(_Primitive);
  23048. Primitives.Box = Box;
  23049. var Sphere = (function (_super) {
  23050. __extends(Sphere, _super);
  23051. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  23052. this.segments = segments;
  23053. this.diameter = diameter;
  23054. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23055. }
  23056. Sphere.prototype._regenerateVertexData = function () {
  23057. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  23058. };
  23059. Sphere.prototype.copy = function (id) {
  23060. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  23061. };
  23062. return Sphere;
  23063. })(_Primitive);
  23064. Primitives.Sphere = Sphere;
  23065. var Cylinder = (function (_super) {
  23066. __extends(Cylinder, _super);
  23067. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  23068. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  23069. this.height = height;
  23070. this.diameterTop = diameterTop;
  23071. this.diameterBottom = diameterBottom;
  23072. this.tessellation = tessellation;
  23073. this.subdivisions = subdivisions;
  23074. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23075. }
  23076. Cylinder.prototype._regenerateVertexData = function () {
  23077. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  23078. };
  23079. Cylinder.prototype.copy = function (id) {
  23080. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  23081. };
  23082. return Cylinder;
  23083. })(_Primitive);
  23084. Primitives.Cylinder = Cylinder;
  23085. var Torus = (function (_super) {
  23086. __extends(Torus, _super);
  23087. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  23088. this.diameter = diameter;
  23089. this.thickness = thickness;
  23090. this.tessellation = tessellation;
  23091. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23092. }
  23093. Torus.prototype._regenerateVertexData = function () {
  23094. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  23095. };
  23096. Torus.prototype.copy = function (id) {
  23097. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  23098. };
  23099. return Torus;
  23100. })(_Primitive);
  23101. Primitives.Torus = Torus;
  23102. var Ground = (function (_super) {
  23103. __extends(Ground, _super);
  23104. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  23105. this.width = width;
  23106. this.height = height;
  23107. this.subdivisions = subdivisions;
  23108. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23109. }
  23110. Ground.prototype._regenerateVertexData = function () {
  23111. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  23112. };
  23113. Ground.prototype.copy = function (id) {
  23114. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  23115. };
  23116. return Ground;
  23117. })(_Primitive);
  23118. Primitives.Ground = Ground;
  23119. var TiledGround = (function (_super) {
  23120. __extends(TiledGround, _super);
  23121. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  23122. this.xmin = xmin;
  23123. this.zmin = zmin;
  23124. this.xmax = xmax;
  23125. this.zmax = zmax;
  23126. this.subdivisions = subdivisions;
  23127. this.precision = precision;
  23128. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23129. }
  23130. TiledGround.prototype._regenerateVertexData = function () {
  23131. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  23132. };
  23133. TiledGround.prototype.copy = function (id) {
  23134. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  23135. };
  23136. return TiledGround;
  23137. })(_Primitive);
  23138. Primitives.TiledGround = TiledGround;
  23139. var Plane = (function (_super) {
  23140. __extends(Plane, _super);
  23141. function Plane(id, scene, size, canBeRegenerated, mesh) {
  23142. this.size = size;
  23143. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23144. }
  23145. Plane.prototype._regenerateVertexData = function () {
  23146. return BABYLON.VertexData.CreatePlane(this.size);
  23147. };
  23148. Plane.prototype.copy = function (id) {
  23149. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23150. };
  23151. return Plane;
  23152. })(_Primitive);
  23153. Primitives.Plane = Plane;
  23154. var TorusKnot = (function (_super) {
  23155. __extends(TorusKnot, _super);
  23156. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  23157. this.radius = radius;
  23158. this.tube = tube;
  23159. this.radialSegments = radialSegments;
  23160. this.tubularSegments = tubularSegments;
  23161. this.p = p;
  23162. this.q = q;
  23163. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23164. }
  23165. TorusKnot.prototype._regenerateVertexData = function () {
  23166. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  23167. };
  23168. TorusKnot.prototype.copy = function (id) {
  23169. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  23170. };
  23171. return TorusKnot;
  23172. })(_Primitive);
  23173. Primitives.TorusKnot = TorusKnot;
  23174. })(Geometry.Primitives || (Geometry.Primitives = {}));
  23175. var Primitives = Geometry.Primitives;
  23176. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  23177. var Geometry = BABYLON.Geometry;
  23178. })(BABYLON || (BABYLON = {}));
  23179. //# sourceMappingURL=babylon.geometry.js.map
  23180. var BABYLON;
  23181. (function (BABYLON) {
  23182. var Gamepads = (function () {
  23183. function Gamepads(ongamedpadconnected) {
  23184. var _this = this;
  23185. this.babylonGamepads = [];
  23186. this.oneGamepadConnected = false;
  23187. this.isMonitoring = false;
  23188. this.gamepadEventSupported = 'GamepadEvent' in window;
  23189. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  23190. 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=";
  23191. this._callbackGamepadConnected = ongamedpadconnected;
  23192. if (this.gamepadSupportAvailable) {
  23193. // Checking if the gamepad connected event is supported (like in Firefox)
  23194. if (this.gamepadEventSupported) {
  23195. window.addEventListener('gamepadconnected', function (evt) {
  23196. _this._onGamepadConnected(evt);
  23197. }, false);
  23198. window.addEventListener('gamepaddisconnected', function (evt) {
  23199. _this._onGamepadDisconnected(evt);
  23200. }, false);
  23201. } else {
  23202. this._startMonitoringGamepads();
  23203. }
  23204. if (!this.oneGamepadConnected) {
  23205. this._insertGamepadDOMInstructions();
  23206. }
  23207. } else {
  23208. this._insertGamepadDOMNotSupported();
  23209. }
  23210. }
  23211. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  23212. Gamepads.gamepadDOMInfo = document.createElement("div");
  23213. var buttonAImage = document.createElement("img");
  23214. buttonAImage.src = this.buttonADataURL;
  23215. var spanMessage = document.createElement("span");
  23216. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  23217. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  23218. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23219. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23220. Gamepads.gamepadDOMInfo.style.width = "100%";
  23221. Gamepads.gamepadDOMInfo.style.height = "48px";
  23222. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23223. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23224. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23225. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23226. buttonAImage.style.position = "relative";
  23227. buttonAImage.style.bottom = "8px";
  23228. spanMessage.style.position = "relative";
  23229. spanMessage.style.fontSize = "32px";
  23230. spanMessage.style.bottom = "32px";
  23231. spanMessage.style.color = "green";
  23232. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23233. };
  23234. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  23235. Gamepads.gamepadDOMInfo = document.createElement("div");
  23236. var spanMessage = document.createElement("span");
  23237. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  23238. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23239. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23240. Gamepads.gamepadDOMInfo.style.width = "100%";
  23241. Gamepads.gamepadDOMInfo.style.height = "40px";
  23242. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23243. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23244. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23245. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23246. spanMessage.style.position = "relative";
  23247. spanMessage.style.fontSize = "32px";
  23248. spanMessage.style.color = "red";
  23249. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23250. };
  23251. Gamepads.prototype.dispose = function () {
  23252. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23253. };
  23254. Gamepads.prototype._onGamepadConnected = function (evt) {
  23255. var newGamepad = this._addNewGamepad(evt.gamepad);
  23256. if (this._callbackGamepadConnected)
  23257. this._callbackGamepadConnected(newGamepad);
  23258. this._startMonitoringGamepads();
  23259. };
  23260. Gamepads.prototype._addNewGamepad = function (gamepad) {
  23261. if (!this.oneGamepadConnected) {
  23262. this.oneGamepadConnected = true;
  23263. if (Gamepads.gamepadDOMInfo) {
  23264. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23265. Gamepads.gamepadDOMInfo = null;
  23266. }
  23267. }
  23268. var newGamepad;
  23269. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  23270. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  23271. } else {
  23272. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  23273. }
  23274. this.babylonGamepads.push(newGamepad);
  23275. return newGamepad;
  23276. };
  23277. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  23278. for (var i in this.babylonGamepads) {
  23279. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  23280. this.babylonGamepads.splice(i, 1);
  23281. break;
  23282. }
  23283. }
  23284. // If no gamepads are left, stop the polling loop.
  23285. if (this.babylonGamepads.length == 0) {
  23286. this._stopMonitoringGamepads();
  23287. }
  23288. };
  23289. Gamepads.prototype._startMonitoringGamepads = function () {
  23290. if (!this.isMonitoring) {
  23291. this.isMonitoring = true;
  23292. this._checkGamepadsStatus();
  23293. }
  23294. };
  23295. Gamepads.prototype._stopMonitoringGamepads = function () {
  23296. this.isMonitoring = false;
  23297. };
  23298. Gamepads.prototype._checkGamepadsStatus = function () {
  23299. var _this = this;
  23300. // updating gamepad objects
  23301. this._updateGamepadObjects();
  23302. for (var i in this.babylonGamepads) {
  23303. this.babylonGamepads[i].update();
  23304. }
  23305. if (this.isMonitoring) {
  23306. if (window.requestAnimationFrame) {
  23307. window.requestAnimationFrame(function () {
  23308. _this._checkGamepadsStatus();
  23309. });
  23310. } else if (window.mozRequestAnimationFrame) {
  23311. window.mozRequestAnimationFrame(function () {
  23312. _this._checkGamepadsStatus();
  23313. });
  23314. } else if (window.webkitRequestAnimationFrame) {
  23315. window.webkitRequestAnimationFrame(function () {
  23316. _this._checkGamepadsStatus();
  23317. });
  23318. }
  23319. }
  23320. };
  23321. // This function is called only on Chrome, which does not yet support
  23322. // connection/disconnection events, but requires you to monitor
  23323. // an array for changes.
  23324. Gamepads.prototype._updateGamepadObjects = function () {
  23325. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  23326. for (var i = 0; i < gamepads.length; i++) {
  23327. if (gamepads[i]) {
  23328. if (!(gamepads[i].index in this.babylonGamepads)) {
  23329. var newGamepad = this._addNewGamepad(gamepads[i]);
  23330. if (this._callbackGamepadConnected) {
  23331. this._callbackGamepadConnected(newGamepad);
  23332. }
  23333. } else {
  23334. this.babylonGamepads[i].browserGamepad = gamepads[i];
  23335. }
  23336. }
  23337. }
  23338. };
  23339. return Gamepads;
  23340. })();
  23341. BABYLON.Gamepads = Gamepads;
  23342. var StickValues = (function () {
  23343. function StickValues(x, y) {
  23344. this.x = x;
  23345. this.y = y;
  23346. }
  23347. return StickValues;
  23348. })();
  23349. BABYLON.StickValues = StickValues;
  23350. var Gamepad = (function () {
  23351. function Gamepad(id, index, browserGamepad) {
  23352. this.id = id;
  23353. this.index = index;
  23354. this.browserGamepad = browserGamepad;
  23355. if (this.browserGamepad.axes.length >= 2) {
  23356. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23357. }
  23358. if (this.browserGamepad.axes.length >= 4) {
  23359. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23360. }
  23361. }
  23362. Gamepad.prototype.onleftstickchanged = function (callback) {
  23363. this._onleftstickchanged = callback;
  23364. };
  23365. Gamepad.prototype.onrightstickchanged = function (callback) {
  23366. this._onrightstickchanged = callback;
  23367. };
  23368. Object.defineProperty(Gamepad.prototype, "leftStick", {
  23369. get: function () {
  23370. return this._leftStick;
  23371. },
  23372. set: function (newValues) {
  23373. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  23374. this._onleftstickchanged(newValues);
  23375. }
  23376. this._leftStick = newValues;
  23377. },
  23378. enumerable: true,
  23379. configurable: true
  23380. });
  23381. Object.defineProperty(Gamepad.prototype, "rightStick", {
  23382. get: function () {
  23383. return this._rightStick;
  23384. },
  23385. set: function (newValues) {
  23386. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  23387. this._onrightstickchanged(newValues);
  23388. }
  23389. this._rightStick = newValues;
  23390. },
  23391. enumerable: true,
  23392. configurable: true
  23393. });
  23394. Gamepad.prototype.update = function () {
  23395. if (this._leftStick) {
  23396. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23397. }
  23398. if (this._rightStick) {
  23399. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23400. }
  23401. };
  23402. return Gamepad;
  23403. })();
  23404. BABYLON.Gamepad = Gamepad;
  23405. var GenericPad = (function (_super) {
  23406. __extends(GenericPad, _super);
  23407. function GenericPad(id, index, gamepad) {
  23408. _super.call(this, id, index, gamepad);
  23409. this.id = id;
  23410. this.index = index;
  23411. this.gamepad = gamepad;
  23412. this._buttons = new Array(gamepad.buttons.length);
  23413. }
  23414. GenericPad.prototype.onbuttondown = function (callback) {
  23415. this._onbuttondown = callback;
  23416. };
  23417. GenericPad.prototype.onbuttonup = function (callback) {
  23418. this._onbuttonup = callback;
  23419. };
  23420. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  23421. if (newValue !== currentValue) {
  23422. if (this._onbuttondown && newValue === 1) {
  23423. this._onbuttondown(buttonIndex);
  23424. }
  23425. if (this._onbuttonup && newValue === 0) {
  23426. this._onbuttonup(buttonIndex);
  23427. }
  23428. }
  23429. return newValue;
  23430. };
  23431. GenericPad.prototype.update = function () {
  23432. _super.prototype.update.call(this);
  23433. for (var index = 0; index < this._buttons.length; index++) {
  23434. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  23435. }
  23436. };
  23437. return GenericPad;
  23438. })(Gamepad);
  23439. BABYLON.GenericPad = GenericPad;
  23440. (function (Xbox360Button) {
  23441. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  23442. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  23443. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  23444. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  23445. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  23446. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  23447. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  23448. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  23449. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  23450. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  23451. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  23452. var Xbox360Button = BABYLON.Xbox360Button;
  23453. (function (Xbox360Dpad) {
  23454. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  23455. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  23456. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  23457. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  23458. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  23459. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  23460. var Xbox360Pad = (function (_super) {
  23461. __extends(Xbox360Pad, _super);
  23462. function Xbox360Pad() {
  23463. _super.apply(this, arguments);
  23464. this._leftTrigger = 0;
  23465. this._rightTrigger = 0;
  23466. this._buttonA = 0;
  23467. this._buttonB = 0;
  23468. this._buttonX = 0;
  23469. this._buttonY = 0;
  23470. this._buttonBack = 0;
  23471. this._buttonStart = 0;
  23472. this._buttonLB = 0;
  23473. this._buttonRB = 0;
  23474. this._buttonLeftStick = 0;
  23475. this._buttonRightStick = 0;
  23476. this._dPadUp = 0;
  23477. this._dPadDown = 0;
  23478. this._dPadLeft = 0;
  23479. this._dPadRight = 0;
  23480. }
  23481. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  23482. this._onlefttriggerchanged = callback;
  23483. };
  23484. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  23485. this._onrighttriggerchanged = callback;
  23486. };
  23487. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  23488. get: function () {
  23489. return this._leftTrigger;
  23490. },
  23491. set: function (newValue) {
  23492. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  23493. this._onlefttriggerchanged(newValue);
  23494. }
  23495. this._leftTrigger = newValue;
  23496. },
  23497. enumerable: true,
  23498. configurable: true
  23499. });
  23500. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  23501. get: function () {
  23502. return this._rightTrigger;
  23503. },
  23504. set: function (newValue) {
  23505. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  23506. this._onrighttriggerchanged(newValue);
  23507. }
  23508. this._rightTrigger = newValue;
  23509. },
  23510. enumerable: true,
  23511. configurable: true
  23512. });
  23513. Xbox360Pad.prototype.onbuttondown = function (callback) {
  23514. this._onbuttondown = callback;
  23515. };
  23516. Xbox360Pad.prototype.onbuttonup = function (callback) {
  23517. this._onbuttonup = callback;
  23518. };
  23519. Xbox360Pad.prototype.ondpaddown = function (callback) {
  23520. this._ondpaddown = callback;
  23521. };
  23522. Xbox360Pad.prototype.ondpadup = function (callback) {
  23523. this._ondpadup = callback;
  23524. };
  23525. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  23526. if (newValue !== currentValue) {
  23527. if (this._onbuttondown && newValue === 1) {
  23528. this._onbuttondown(buttonType);
  23529. }
  23530. if (this._onbuttonup && newValue === 0) {
  23531. this._onbuttonup(buttonType);
  23532. }
  23533. }
  23534. return newValue;
  23535. };
  23536. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  23537. if (newValue !== currentValue) {
  23538. if (this._ondpaddown && newValue === 1) {
  23539. this._ondpaddown(buttonType);
  23540. }
  23541. if (this._ondpadup && newValue === 0) {
  23542. this._ondpadup(buttonType);
  23543. }
  23544. }
  23545. return newValue;
  23546. };
  23547. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  23548. get: function () {
  23549. return this._buttonA;
  23550. },
  23551. set: function (value) {
  23552. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  23553. },
  23554. enumerable: true,
  23555. configurable: true
  23556. });
  23557. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  23558. get: function () {
  23559. return this._buttonB;
  23560. },
  23561. set: function (value) {
  23562. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  23563. },
  23564. enumerable: true,
  23565. configurable: true
  23566. });
  23567. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  23568. get: function () {
  23569. return this._buttonX;
  23570. },
  23571. set: function (value) {
  23572. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  23573. },
  23574. enumerable: true,
  23575. configurable: true
  23576. });
  23577. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  23578. get: function () {
  23579. return this._buttonY;
  23580. },
  23581. set: function (value) {
  23582. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  23583. },
  23584. enumerable: true,
  23585. configurable: true
  23586. });
  23587. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  23588. get: function () {
  23589. return this._buttonStart;
  23590. },
  23591. set: function (value) {
  23592. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  23593. },
  23594. enumerable: true,
  23595. configurable: true
  23596. });
  23597. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  23598. get: function () {
  23599. return this._buttonBack;
  23600. },
  23601. set: function (value) {
  23602. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  23603. },
  23604. enumerable: true,
  23605. configurable: true
  23606. });
  23607. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  23608. get: function () {
  23609. return this._buttonLB;
  23610. },
  23611. set: function (value) {
  23612. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  23613. },
  23614. enumerable: true,
  23615. configurable: true
  23616. });
  23617. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  23618. get: function () {
  23619. return this._buttonRB;
  23620. },
  23621. set: function (value) {
  23622. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  23623. },
  23624. enumerable: true,
  23625. configurable: true
  23626. });
  23627. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  23628. get: function () {
  23629. return this._buttonLeftStick;
  23630. },
  23631. set: function (value) {
  23632. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  23633. },
  23634. enumerable: true,
  23635. configurable: true
  23636. });
  23637. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  23638. get: function () {
  23639. return this._buttonRightStick;
  23640. },
  23641. set: function (value) {
  23642. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  23643. },
  23644. enumerable: true,
  23645. configurable: true
  23646. });
  23647. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  23648. get: function () {
  23649. return this._dPadUp;
  23650. },
  23651. set: function (value) {
  23652. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  23653. },
  23654. enumerable: true,
  23655. configurable: true
  23656. });
  23657. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  23658. get: function () {
  23659. return this._dPadDown;
  23660. },
  23661. set: function (value) {
  23662. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  23663. },
  23664. enumerable: true,
  23665. configurable: true
  23666. });
  23667. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  23668. get: function () {
  23669. return this._dPadLeft;
  23670. },
  23671. set: function (value) {
  23672. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  23673. },
  23674. enumerable: true,
  23675. configurable: true
  23676. });
  23677. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  23678. get: function () {
  23679. return this._dPadRight;
  23680. },
  23681. set: function (value) {
  23682. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  23683. },
  23684. enumerable: true,
  23685. configurable: true
  23686. });
  23687. Xbox360Pad.prototype.update = function () {
  23688. _super.prototype.update.call(this);
  23689. this.buttonA = this.browserGamepad.buttons[0].value;
  23690. this.buttonB = this.browserGamepad.buttons[1].value;
  23691. this.buttonX = this.browserGamepad.buttons[2].value;
  23692. this.buttonY = this.browserGamepad.buttons[3].value;
  23693. this.buttonLB = this.browserGamepad.buttons[4].value;
  23694. this.buttonRB = this.browserGamepad.buttons[5].value;
  23695. this.leftTrigger = this.browserGamepad.buttons[6].value;
  23696. this.rightTrigger = this.browserGamepad.buttons[7].value;
  23697. this.buttonBack = this.browserGamepad.buttons[8].value;
  23698. this.buttonStart = this.browserGamepad.buttons[9].value;
  23699. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  23700. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  23701. this.dPadUp = this.browserGamepad.buttons[12].value;
  23702. this.dPadDown = this.browserGamepad.buttons[13].value;
  23703. this.dPadLeft = this.browserGamepad.buttons[14].value;
  23704. this.dPadRight = this.browserGamepad.buttons[15].value;
  23705. };
  23706. return Xbox360Pad;
  23707. })(Gamepad);
  23708. BABYLON.Xbox360Pad = Xbox360Pad;
  23709. })(BABYLON || (BABYLON = {}));
  23710. //# sourceMappingURL=babylon.gamepads.js.map
  23711. var BABYLON;
  23712. (function (BABYLON) {
  23713. // We're mainly based on the logic defined into the FreeCamera code
  23714. var GamepadCamera = (function (_super) {
  23715. __extends(GamepadCamera, _super);
  23716. function GamepadCamera(name, position, scene) {
  23717. var _this = this;
  23718. _super.call(this, name, position, scene);
  23719. this.angularSensibility = 200;
  23720. this.moveSensibility = 75;
  23721. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23722. _this._onNewGameConnected(gamepad);
  23723. });
  23724. }
  23725. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23726. // Only the first gamepad can control the camera
  23727. if (gamepad.index === 0) {
  23728. this._gamepad = gamepad;
  23729. }
  23730. };
  23731. GamepadCamera.prototype._checkInputs = function () {
  23732. if (!this._gamepad) {
  23733. return;
  23734. }
  23735. var LSValues = this._gamepad.leftStick;
  23736. var normalizedLX = LSValues.x / this.moveSensibility;
  23737. var normalizedLY = LSValues.y / this.moveSensibility;
  23738. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23739. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23740. var RSValues = this._gamepad.rightStick;
  23741. var normalizedRX = RSValues.x / this.angularSensibility;
  23742. var normalizedRY = RSValues.y / this.angularSensibility;
  23743. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  23744. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  23745. ;
  23746. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23747. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23748. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23749. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  23750. };
  23751. GamepadCamera.prototype.dispose = function () {
  23752. this._gamepads.dispose();
  23753. _super.prototype.dispose.call(this);
  23754. };
  23755. return GamepadCamera;
  23756. })(BABYLON.FreeCamera);
  23757. BABYLON.GamepadCamera = GamepadCamera;
  23758. })(BABYLON || (BABYLON = {}));
  23759. //# sourceMappingURL=babylon.gamepadCamera.js.map
  23760. var BABYLON;
  23761. (function (BABYLON) {
  23762. var LinesMesh = (function (_super) {
  23763. __extends(LinesMesh, _super);
  23764. function LinesMesh(name, scene, updatable) {
  23765. if (typeof updatable === "undefined") { updatable = false; }
  23766. _super.call(this, name, scene);
  23767. this.color = new BABYLON.Color3(1, 1, 1);
  23768. this.alpha = 1;
  23769. this._indices = new Array();
  23770. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23771. attributes: ["position"],
  23772. uniforms: ["worldViewProjection", "color"],
  23773. needAlphaBlending: true
  23774. });
  23775. }
  23776. Object.defineProperty(LinesMesh.prototype, "material", {
  23777. get: function () {
  23778. return this._colorShader;
  23779. },
  23780. enumerable: true,
  23781. configurable: true
  23782. });
  23783. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  23784. get: function () {
  23785. return false;
  23786. },
  23787. enumerable: true,
  23788. configurable: true
  23789. });
  23790. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  23791. get: function () {
  23792. return false;
  23793. },
  23794. enumerable: true,
  23795. configurable: true
  23796. });
  23797. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  23798. var engine = this.getScene().getEngine();
  23799. var indexToBind = this._geometry.getIndexBuffer();
  23800. // VBOs
  23801. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  23802. // Color
  23803. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  23804. };
  23805. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23806. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23807. return;
  23808. }
  23809. var engine = this.getScene().getEngine();
  23810. // Draw order
  23811. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  23812. };
  23813. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  23814. return null;
  23815. };
  23816. LinesMesh.prototype.dispose = function (doNotRecurse) {
  23817. this._colorShader.dispose();
  23818. _super.prototype.dispose.call(this, doNotRecurse);
  23819. };
  23820. return LinesMesh;
  23821. })(BABYLON.Mesh);
  23822. BABYLON.LinesMesh = LinesMesh;
  23823. })(BABYLON || (BABYLON = {}));
  23824. //# sourceMappingURL=babylon.linesMesh.js.map
  23825. var BABYLON;
  23826. (function (BABYLON) {
  23827. var OutlineRenderer = (function () {
  23828. function OutlineRenderer(scene) {
  23829. this._scene = scene;
  23830. }
  23831. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  23832. if (typeof useOverlay === "undefined") { useOverlay = false; }
  23833. var scene = this._scene;
  23834. var engine = this._scene.getEngine();
  23835. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23836. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  23837. return;
  23838. }
  23839. var mesh = subMesh.getRenderingMesh();
  23840. var material = subMesh.getMaterial();
  23841. engine.enableEffect(this._effect);
  23842. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  23843. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  23844. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23845. // Bones
  23846. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  23847. if (useBones) {
  23848. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23849. }
  23850. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  23851. // Alpha test
  23852. if (material && material.needAlphaTesting()) {
  23853. var alphaTexture = material.getAlphaTestTexture();
  23854. this._effect.setTexture("diffuseSampler", alphaTexture);
  23855. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  23856. }
  23857. if (hardwareInstancedRendering) {
  23858. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  23859. } else {
  23860. if (batch.renderSelf[subMesh._id]) {
  23861. this._effect.setMatrix("world", mesh.getWorldMatrix());
  23862. // Draw
  23863. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23864. }
  23865. if (batch.visibleInstances[subMesh._id]) {
  23866. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23867. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23868. this._effect.setMatrix("world", instance.getWorldMatrix());
  23869. // Draw
  23870. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23871. }
  23872. }
  23873. }
  23874. };
  23875. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  23876. var defines = [];
  23877. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  23878. var mesh = subMesh.getMesh();
  23879. var material = subMesh.getMaterial();
  23880. // Alpha test
  23881. if (material && material.needAlphaTesting()) {
  23882. defines.push("#define ALPHATEST");
  23883. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23884. attribs.push(BABYLON.VertexBuffer.UVKind);
  23885. defines.push("#define UV1");
  23886. }
  23887. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23888. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23889. defines.push("#define UV2");
  23890. }
  23891. }
  23892. // Bones
  23893. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23894. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23895. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23896. defines.push("#define BONES");
  23897. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23898. }
  23899. // Instances
  23900. if (useInstances) {
  23901. defines.push("#define INSTANCES");
  23902. attribs.push("world0");
  23903. attribs.push("world1");
  23904. attribs.push("world2");
  23905. attribs.push("world3");
  23906. }
  23907. // Get correct effect
  23908. var join = defines.join("\n");
  23909. if (this._cachedDefines != join) {
  23910. this._cachedDefines = join;
  23911. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  23912. }
  23913. return this._effect.isReady();
  23914. };
  23915. return OutlineRenderer;
  23916. })();
  23917. BABYLON.OutlineRenderer = OutlineRenderer;
  23918. })(BABYLON || (BABYLON = {}));
  23919. //# sourceMappingURL=babylon.outlineRenderer.js.map
  23920. var BABYLON;
  23921. (function (BABYLON) {
  23922. var MeshAssetTask = (function () {
  23923. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  23924. this.name = name;
  23925. this.meshesNames = meshesNames;
  23926. this.rootUrl = rootUrl;
  23927. this.sceneFilename = sceneFilename;
  23928. this.isCompleted = false;
  23929. }
  23930. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23931. var _this = this;
  23932. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  23933. _this.loadedMeshes = meshes;
  23934. _this.loadedParticleSystems = particleSystems;
  23935. _this.loadedSkeletons = skeletons;
  23936. _this.isCompleted = true;
  23937. if (_this.onSuccess) {
  23938. _this.onSuccess(_this);
  23939. }
  23940. onSuccess();
  23941. }, null, function () {
  23942. if (_this.onError) {
  23943. _this.onError(_this);
  23944. }
  23945. onError();
  23946. });
  23947. };
  23948. return MeshAssetTask;
  23949. })();
  23950. BABYLON.MeshAssetTask = MeshAssetTask;
  23951. var TextFileAssetTask = (function () {
  23952. function TextFileAssetTask(name, url) {
  23953. this.name = name;
  23954. this.url = url;
  23955. this.isCompleted = false;
  23956. }
  23957. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23958. var _this = this;
  23959. BABYLON.Tools.LoadFile(this.url, function (data) {
  23960. _this.text = data;
  23961. _this.isCompleted = true;
  23962. if (_this.onSuccess) {
  23963. _this.onSuccess(_this);
  23964. }
  23965. onSuccess();
  23966. }, null, scene.database, false, function () {
  23967. if (_this.onError) {
  23968. _this.onError(_this);
  23969. }
  23970. onError();
  23971. });
  23972. };
  23973. return TextFileAssetTask;
  23974. })();
  23975. BABYLON.TextFileAssetTask = TextFileAssetTask;
  23976. var BinaryFileAssetTask = (function () {
  23977. function BinaryFileAssetTask(name, url) {
  23978. this.name = name;
  23979. this.url = url;
  23980. this.isCompleted = false;
  23981. }
  23982. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23983. var _this = this;
  23984. BABYLON.Tools.LoadFile(this.url, function (data) {
  23985. _this.data = data;
  23986. _this.isCompleted = true;
  23987. if (_this.onSuccess) {
  23988. _this.onSuccess(_this);
  23989. }
  23990. onSuccess();
  23991. }, null, scene.database, true, function () {
  23992. if (_this.onError) {
  23993. _this.onError(_this);
  23994. }
  23995. onError();
  23996. });
  23997. };
  23998. return BinaryFileAssetTask;
  23999. })();
  24000. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  24001. var ImageAssetTask = (function () {
  24002. function ImageAssetTask(name, url) {
  24003. this.name = name;
  24004. this.url = url;
  24005. this.isCompleted = false;
  24006. }
  24007. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24008. var _this = this;
  24009. var img = new Image();
  24010. img.onload = function () {
  24011. _this.image = img;
  24012. _this.isCompleted = true;
  24013. if (_this.onSuccess) {
  24014. _this.onSuccess(_this);
  24015. }
  24016. onSuccess();
  24017. };
  24018. img.onerror = function () {
  24019. if (_this.onError) {
  24020. _this.onError(_this);
  24021. }
  24022. onError();
  24023. };
  24024. img.src = this.url;
  24025. };
  24026. return ImageAssetTask;
  24027. })();
  24028. BABYLON.ImageAssetTask = ImageAssetTask;
  24029. var TextureAssetTask = (function () {
  24030. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  24031. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24032. this.name = name;
  24033. this.url = url;
  24034. this.noMipmap = noMipmap;
  24035. this.invertY = invertY;
  24036. this.samplingMode = samplingMode;
  24037. this.isCompleted = false;
  24038. }
  24039. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24040. var _this = this;
  24041. var onload = function () {
  24042. _this.isCompleted = true;
  24043. if (_this.onSuccess) {
  24044. _this.onSuccess(_this);
  24045. }
  24046. onSuccess();
  24047. };
  24048. var onerror = function () {
  24049. if (_this.onError) {
  24050. _this.onError(_this);
  24051. }
  24052. onError();
  24053. };
  24054. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  24055. };
  24056. return TextureAssetTask;
  24057. })();
  24058. BABYLON.TextureAssetTask = TextureAssetTask;
  24059. var AssetsManager = (function () {
  24060. function AssetsManager(scene) {
  24061. this._tasks = new Array();
  24062. this._waitingTasksCount = 0;
  24063. this.useDefaultLoadingScreen = true;
  24064. this._scene = scene;
  24065. }
  24066. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  24067. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  24068. this._tasks.push(task);
  24069. return task;
  24070. };
  24071. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  24072. var task = new TextFileAssetTask(taskName, url);
  24073. this._tasks.push(task);
  24074. return task;
  24075. };
  24076. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  24077. var task = new BinaryFileAssetTask(taskName, url);
  24078. this._tasks.push(task);
  24079. return task;
  24080. };
  24081. AssetsManager.prototype.addImageTask = function (taskName, url) {
  24082. var task = new ImageAssetTask(taskName, url);
  24083. this._tasks.push(task);
  24084. return task;
  24085. };
  24086. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  24087. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24088. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  24089. this._tasks.push(task);
  24090. return task;
  24091. };
  24092. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  24093. this._waitingTasksCount--;
  24094. if (this._waitingTasksCount === 0) {
  24095. if (this.onFinish) {
  24096. this.onFinish(this._tasks);
  24097. }
  24098. this._scene.getEngine().hideLoadingUI();
  24099. }
  24100. };
  24101. AssetsManager.prototype._runTask = function (task) {
  24102. var _this = this;
  24103. task.run(this._scene, function () {
  24104. if (_this.onTaskSuccess) {
  24105. _this.onTaskSuccess(task);
  24106. }
  24107. _this._decreaseWaitingTasksCount();
  24108. }, function () {
  24109. if (_this.onTaskError) {
  24110. _this.onTaskError(task);
  24111. }
  24112. _this._decreaseWaitingTasksCount();
  24113. });
  24114. };
  24115. AssetsManager.prototype.reset = function () {
  24116. this._tasks = new Array();
  24117. return this;
  24118. };
  24119. AssetsManager.prototype.load = function () {
  24120. this._waitingTasksCount = this._tasks.length;
  24121. if (this._waitingTasksCount === 0) {
  24122. if (this.onFinish) {
  24123. this.onFinish(this._tasks);
  24124. }
  24125. return this;
  24126. }
  24127. if (this.useDefaultLoadingScreen) {
  24128. this._scene.getEngine().displayLoadingUI();
  24129. }
  24130. for (var index = 0; index < this._tasks.length; index++) {
  24131. var task = this._tasks[index];
  24132. this._runTask(task);
  24133. }
  24134. return this;
  24135. };
  24136. return AssetsManager;
  24137. })();
  24138. BABYLON.AssetsManager = AssetsManager;
  24139. })(BABYLON || (BABYLON = {}));
  24140. //# sourceMappingURL=babylon.assetsManager.js.map
  24141. var BABYLON;
  24142. (function (BABYLON) {
  24143. var VRDeviceOrientationCamera = (function (_super) {
  24144. __extends(VRDeviceOrientationCamera, _super);
  24145. function VRDeviceOrientationCamera(name, position, scene) {
  24146. _super.call(this, name, position, scene);
  24147. this._alpha = 0;
  24148. this._beta = 0;
  24149. this._gamma = 0;
  24150. }
  24151. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  24152. this._alpha = +evt.alpha | 0;
  24153. this._beta = +evt.beta | 0;
  24154. this._gamma = +evt.gamma | 0;
  24155. if (this._gamma < 0) {
  24156. this._gamma = 90 + this._gamma;
  24157. } else {
  24158. // Incline it in the correct angle.
  24159. this._gamma = 270 - this._gamma;
  24160. }
  24161. this.rotation.x = this._gamma / 180.0 * Math.PI;
  24162. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  24163. this.rotation.z = this._beta / 180.0 * Math.PI;
  24164. };
  24165. return VRDeviceOrientationCamera;
  24166. })(BABYLON.OculusCamera);
  24167. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  24168. })(BABYLON || (BABYLON = {}));
  24169. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  24170. var BABYLON;
  24171. (function (BABYLON) {
  24172. var WebVRCamera = (function (_super) {
  24173. __extends(WebVRCamera, _super);
  24174. function WebVRCamera(name, position, scene) {
  24175. _super.call(this, name, position, scene);
  24176. this._hmdDevice = null;
  24177. this._sensorDevice = null;
  24178. this._cacheState = null;
  24179. this._cacheQuaternion = new BABYLON.Quaternion();
  24180. this._cacheRotation = BABYLON.Vector3.Zero();
  24181. this._vrEnabled = false;
  24182. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  24183. }
  24184. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  24185. var size = devices.length;
  24186. var i = 0;
  24187. // Reset devices.
  24188. this._sensorDevice = null;
  24189. this._hmdDevice = null;
  24190. while (i < size && this._hmdDevice === null) {
  24191. if (devices[i] instanceof HMDVRDevice) {
  24192. this._hmdDevice = devices[i];
  24193. }
  24194. i++;
  24195. }
  24196. i = 0;
  24197. while (i < size && this._sensorDevice === null) {
  24198. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  24199. this._sensorDevice = devices[i];
  24200. }
  24201. i++;
  24202. }
  24203. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  24204. };
  24205. WebVRCamera.prototype._update = function () {
  24206. if (this._vrEnabled) {
  24207. this._cacheState = this._sensorDevice.getState();
  24208. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  24209. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  24210. this.rotation.x = -this._cacheRotation.z;
  24211. this.rotation.y = -this._cacheRotation.y;
  24212. this.rotation.z = this._cacheRotation.x;
  24213. }
  24214. _super.prototype._update.call(this);
  24215. };
  24216. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  24217. _super.prototype.attachControl.call(this, element, noPreventDefault);
  24218. if (navigator.getVRDevices) {
  24219. navigator.getVRDevices().then(this._getWebVRDevices);
  24220. } else if (navigator.mozGetVRDevices) {
  24221. navigator.mozGetVRDevices(this._getWebVRDevices);
  24222. }
  24223. };
  24224. WebVRCamera.prototype.detachControl = function (element) {
  24225. _super.prototype.detachControl.call(this, element);
  24226. this._vrEnabled = false;
  24227. };
  24228. return WebVRCamera;
  24229. })(BABYLON.OculusCamera);
  24230. BABYLON.WebVRCamera = WebVRCamera;
  24231. })(BABYLON || (BABYLON = {}));
  24232. //# sourceMappingURL=babylon.webVRCamera.js.map
  24233. var BABYLON;
  24234. (function (BABYLON) {
  24235. // Standard optimizations
  24236. var SceneOptimization = (function () {
  24237. function SceneOptimization(priority) {
  24238. if (typeof priority === "undefined") { priority = 0; }
  24239. this.priority = priority;
  24240. this.apply = function (scene) {
  24241. return true;
  24242. };
  24243. }
  24244. return SceneOptimization;
  24245. })();
  24246. BABYLON.SceneOptimization = SceneOptimization;
  24247. var TextureOptimization = (function (_super) {
  24248. __extends(TextureOptimization, _super);
  24249. function TextureOptimization(priority, maximumSize) {
  24250. if (typeof priority === "undefined") { priority = 0; }
  24251. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  24252. var _this = this;
  24253. _super.call(this, priority);
  24254. this.priority = priority;
  24255. this.maximumSize = maximumSize;
  24256. this.apply = function (scene) {
  24257. var allDone = true;
  24258. for (var index = 0; index < scene.textures.length; index++) {
  24259. var texture = scene.textures[index];
  24260. if (!texture.canRescale) {
  24261. continue;
  24262. }
  24263. var currentSize = texture.getSize();
  24264. var maxDimension = Math.max(currentSize.width, currentSize.height);
  24265. if (maxDimension > _this.maximumSize) {
  24266. texture.scale(0.5);
  24267. allDone = false;
  24268. }
  24269. }
  24270. return allDone;
  24271. };
  24272. }
  24273. return TextureOptimization;
  24274. })(SceneOptimization);
  24275. BABYLON.TextureOptimization = TextureOptimization;
  24276. var HardwareScalingOptimization = (function (_super) {
  24277. __extends(HardwareScalingOptimization, _super);
  24278. function HardwareScalingOptimization(priority, maximumScale) {
  24279. if (typeof priority === "undefined") { priority = 0; }
  24280. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  24281. var _this = this;
  24282. _super.call(this, priority);
  24283. this.priority = priority;
  24284. this.maximumScale = maximumScale;
  24285. this._currentScale = 1;
  24286. this.apply = function (scene) {
  24287. _this._currentScale++;
  24288. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  24289. return _this._currentScale >= _this.maximumScale;
  24290. };
  24291. }
  24292. return HardwareScalingOptimization;
  24293. })(SceneOptimization);
  24294. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  24295. var ShadowsOptimization = (function (_super) {
  24296. __extends(ShadowsOptimization, _super);
  24297. function ShadowsOptimization() {
  24298. _super.apply(this, arguments);
  24299. this.apply = function (scene) {
  24300. scene.shadowsEnabled = false;
  24301. return true;
  24302. };
  24303. }
  24304. return ShadowsOptimization;
  24305. })(SceneOptimization);
  24306. BABYLON.ShadowsOptimization = ShadowsOptimization;
  24307. var PostProcessesOptimization = (function (_super) {
  24308. __extends(PostProcessesOptimization, _super);
  24309. function PostProcessesOptimization() {
  24310. _super.apply(this, arguments);
  24311. this.apply = function (scene) {
  24312. scene.postProcessesEnabled = false;
  24313. return true;
  24314. };
  24315. }
  24316. return PostProcessesOptimization;
  24317. })(SceneOptimization);
  24318. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  24319. var LensFlaresOptimization = (function (_super) {
  24320. __extends(LensFlaresOptimization, _super);
  24321. function LensFlaresOptimization() {
  24322. _super.apply(this, arguments);
  24323. this.apply = function (scene) {
  24324. scene.lensFlaresEnabled = false;
  24325. return true;
  24326. };
  24327. }
  24328. return LensFlaresOptimization;
  24329. })(SceneOptimization);
  24330. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  24331. var ParticlesOptimization = (function (_super) {
  24332. __extends(ParticlesOptimization, _super);
  24333. function ParticlesOptimization() {
  24334. _super.apply(this, arguments);
  24335. this.apply = function (scene) {
  24336. scene.particlesEnabled = false;
  24337. return true;
  24338. };
  24339. }
  24340. return ParticlesOptimization;
  24341. })(SceneOptimization);
  24342. BABYLON.ParticlesOptimization = ParticlesOptimization;
  24343. var RenderTargetsOptimization = (function (_super) {
  24344. __extends(RenderTargetsOptimization, _super);
  24345. function RenderTargetsOptimization() {
  24346. _super.apply(this, arguments);
  24347. this.apply = function (scene) {
  24348. scene.renderTargetsEnabled = false;
  24349. return true;
  24350. };
  24351. }
  24352. return RenderTargetsOptimization;
  24353. })(SceneOptimization);
  24354. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  24355. var MergeMeshesOptimization = (function (_super) {
  24356. __extends(MergeMeshesOptimization, _super);
  24357. function MergeMeshesOptimization() {
  24358. _super.apply(this, arguments);
  24359. var _this = this;
  24360. this._canBeMerged = function (abstractMesh) {
  24361. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  24362. return false;
  24363. }
  24364. var mesh = abstractMesh;
  24365. if (!mesh.isVisible || !mesh.isEnabled()) {
  24366. return false;
  24367. }
  24368. if (mesh.instances.length > 0) {
  24369. return false;
  24370. }
  24371. if (mesh.skeleton || mesh.hasLODLevels) {
  24372. return false;
  24373. }
  24374. return true;
  24375. };
  24376. this.apply = function (scene) {
  24377. var globalPool = scene.meshes.slice(0);
  24378. var globalLength = globalPool.length;
  24379. for (var index = 0; index < globalLength; index++) {
  24380. var currentPool = new Array();
  24381. var current = globalPool[index];
  24382. // Checks
  24383. if (!_this._canBeMerged(current)) {
  24384. continue;
  24385. }
  24386. currentPool.push(current);
  24387. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  24388. var otherMesh = globalPool[subIndex];
  24389. if (!_this._canBeMerged(otherMesh)) {
  24390. continue;
  24391. }
  24392. if (otherMesh.material !== current.material) {
  24393. continue;
  24394. }
  24395. if (otherMesh.checkCollisions !== current.checkCollisions) {
  24396. continue;
  24397. }
  24398. currentPool.push(otherMesh);
  24399. globalLength--;
  24400. globalPool.splice(subIndex, 1);
  24401. subIndex--;
  24402. }
  24403. if (currentPool.length < 2) {
  24404. continue;
  24405. }
  24406. // Merge meshes
  24407. BABYLON.Mesh.MergeMeshes(currentPool);
  24408. }
  24409. return true;
  24410. };
  24411. }
  24412. return MergeMeshesOptimization;
  24413. })(SceneOptimization);
  24414. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  24415. // Options
  24416. var SceneOptimizerOptions = (function () {
  24417. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  24418. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  24419. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  24420. this.targetFrameRate = targetFrameRate;
  24421. this.trackerDuration = trackerDuration;
  24422. this.optimizations = new Array();
  24423. }
  24424. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  24425. var result = new SceneOptimizerOptions(targetFrameRate);
  24426. var priority = 0;
  24427. result.optimizations.push(new MergeMeshesOptimization(priority));
  24428. result.optimizations.push(new ShadowsOptimization(priority));
  24429. result.optimizations.push(new LensFlaresOptimization(priority));
  24430. // Next priority
  24431. priority++;
  24432. result.optimizations.push(new PostProcessesOptimization(priority));
  24433. result.optimizations.push(new ParticlesOptimization(priority));
  24434. // Next priority
  24435. priority++;
  24436. result.optimizations.push(new TextureOptimization(priority, 1024));
  24437. return result;
  24438. };
  24439. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  24440. var result = new SceneOptimizerOptions(targetFrameRate);
  24441. var priority = 0;
  24442. result.optimizations.push(new MergeMeshesOptimization(priority));
  24443. result.optimizations.push(new ShadowsOptimization(priority));
  24444. result.optimizations.push(new LensFlaresOptimization(priority));
  24445. // Next priority
  24446. priority++;
  24447. result.optimizations.push(new PostProcessesOptimization(priority));
  24448. result.optimizations.push(new ParticlesOptimization(priority));
  24449. // Next priority
  24450. priority++;
  24451. result.optimizations.push(new TextureOptimization(priority, 512));
  24452. // Next priority
  24453. priority++;
  24454. result.optimizations.push(new RenderTargetsOptimization(priority));
  24455. // Next priority
  24456. priority++;
  24457. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  24458. return result;
  24459. };
  24460. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  24461. var result = new SceneOptimizerOptions(targetFrameRate);
  24462. var priority = 0;
  24463. result.optimizations.push(new MergeMeshesOptimization(priority));
  24464. result.optimizations.push(new ShadowsOptimization(priority));
  24465. result.optimizations.push(new LensFlaresOptimization(priority));
  24466. // Next priority
  24467. priority++;
  24468. result.optimizations.push(new PostProcessesOptimization(priority));
  24469. result.optimizations.push(new ParticlesOptimization(priority));
  24470. // Next priority
  24471. priority++;
  24472. result.optimizations.push(new TextureOptimization(priority, 256));
  24473. // Next priority
  24474. priority++;
  24475. result.optimizations.push(new RenderTargetsOptimization(priority));
  24476. // Next priority
  24477. priority++;
  24478. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  24479. return result;
  24480. };
  24481. return SceneOptimizerOptions;
  24482. })();
  24483. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  24484. // Scene optimizer tool
  24485. var SceneOptimizer = (function () {
  24486. function SceneOptimizer() {
  24487. }
  24488. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  24489. // TODO: add an epsilon
  24490. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  24491. if (onSuccess) {
  24492. onSuccess();
  24493. }
  24494. return;
  24495. }
  24496. // Apply current level of optimizations
  24497. var allDone = true;
  24498. var noOptimizationApplied = true;
  24499. for (var index = 0; index < options.optimizations.length; index++) {
  24500. var optimization = options.optimizations[index];
  24501. if (optimization.priority === currentPriorityLevel) {
  24502. noOptimizationApplied = false;
  24503. allDone = allDone && optimization.apply(scene);
  24504. }
  24505. }
  24506. // If no optimization was applied, this is a failure :(
  24507. if (noOptimizationApplied) {
  24508. if (onFailure) {
  24509. onFailure();
  24510. }
  24511. return;
  24512. }
  24513. // If all optimizations were done, move to next level
  24514. if (allDone) {
  24515. currentPriorityLevel++;
  24516. }
  24517. // Let's the system running for a specific amount of time before checking FPS
  24518. scene.executeWhenReady(function () {
  24519. setTimeout(function () {
  24520. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  24521. }, options.trackerDuration);
  24522. });
  24523. };
  24524. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  24525. if (!options) {
  24526. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  24527. }
  24528. // Let's the system running for a specific amount of time before checking FPS
  24529. scene.executeWhenReady(function () {
  24530. setTimeout(function () {
  24531. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  24532. }, options.trackerDuration);
  24533. });
  24534. };
  24535. return SceneOptimizer;
  24536. })();
  24537. BABYLON.SceneOptimizer = SceneOptimizer;
  24538. })(BABYLON || (BABYLON = {}));
  24539. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  24540. var BABYLON;
  24541. (function (BABYLON) {
  24542. (function (Internals) {
  24543. var MeshLODLevel = (function () {
  24544. function MeshLODLevel(distance, mesh) {
  24545. this.distance = distance;
  24546. this.mesh = mesh;
  24547. }
  24548. return MeshLODLevel;
  24549. })();
  24550. Internals.MeshLODLevel = MeshLODLevel;
  24551. })(BABYLON.Internals || (BABYLON.Internals = {}));
  24552. var Internals = BABYLON.Internals;
  24553. })(BABYLON || (BABYLON = {}));
  24554. //# sourceMappingURL=babylon.meshLODLevel.js.map
  24555. var BABYLON;
  24556. (function (BABYLON) {
  24557. var AudioEngine = (function () {
  24558. function AudioEngine() {
  24559. this.audioContext = null;
  24560. this.canUseWebAudio = false;
  24561. try {
  24562. if (typeof AudioContext !== 'undefined') {
  24563. this.audioContext = new AudioContext();
  24564. this.canUseWebAudio = true;
  24565. } else if (typeof webkitAudioContext !== 'undefined') {
  24566. this.audioContext = new webkitAudioContext();
  24567. this.canUseWebAudio = true;
  24568. }
  24569. } catch (e) {
  24570. this.canUseWebAudio = false;
  24571. BABYLON.Tools.Error("Your browser doesn't support Web Audio.");
  24572. }
  24573. // create a global volume gain node
  24574. if (this.canUseWebAudio) {
  24575. this.masterGain = this.audioContext.createGain();
  24576. this.masterGain.gain.value = 1;
  24577. this.masterGain.connect(this.audioContext.destination);
  24578. }
  24579. }
  24580. AudioEngine.prototype.getGlobalVolume = function () {
  24581. if (this.canUseWebAudio) {
  24582. return this.masterGain.gain.value;
  24583. } else {
  24584. return -1;
  24585. }
  24586. };
  24587. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  24588. if (this.canUseWebAudio) {
  24589. this.masterGain.gain.value = newVolume;
  24590. }
  24591. };
  24592. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  24593. if (this.canUseWebAudio) {
  24594. this.masterGain.disconnect();
  24595. analyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  24596. }
  24597. };
  24598. return AudioEngine;
  24599. })();
  24600. BABYLON.AudioEngine = AudioEngine;
  24601. })(BABYLON || (BABYLON = {}));
  24602. //# sourceMappingURL=babylon.audioengine.js.map
  24603. var BABYLON;
  24604. (function (BABYLON) {
  24605. var Sound = (function () {
  24606. /**
  24607. * Create a sound and attach it to a scene
  24608. * @param name Name of your sound
  24609. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  24610. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  24611. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  24612. */
  24613. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  24614. var _this = this;
  24615. this.autoplay = false;
  24616. this.loop = false;
  24617. this.useCustomAttenuation = false;
  24618. this.spatialSound = false;
  24619. this.refDistance = 1;
  24620. this.rolloffFactor = 1;
  24621. this.maxDistance = 100;
  24622. this.distanceModel = "linear";
  24623. this.panningModel = "HRTF";
  24624. this.startTime = 0;
  24625. this.startOffset = 0;
  24626. this._position = BABYLON.Vector3.Zero();
  24627. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  24628. this._volume = 1;
  24629. this._isLoaded = false;
  24630. this._isReadyToPlay = false;
  24631. this._isPlaying = false;
  24632. this._isDirectional = false;
  24633. // Used if you'd like to create a directional sound.
  24634. // If not set, the sound will be omnidirectional
  24635. this._coneInnerAngle = 360;
  24636. this._coneOuterAngle = 360;
  24637. this._coneOuterGain = 0;
  24638. this._name = name;
  24639. this._scene = scene;
  24640. this._audioEngine = this._scene.getEngine().getAudioEngine();
  24641. this._readyToPlayCallback = readyToPlayCallback;
  24642. // Default custom attenuation function is a linear attenuation
  24643. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  24644. if (currentDistance < maxDistance) {
  24645. return currentVolume * (1 - currentDistance / maxDistance);
  24646. } else {
  24647. return 0;
  24648. }
  24649. };
  24650. if (options) {
  24651. this.autoplay = options.autoplay || false;
  24652. this.loop = options.loop || false;
  24653. this._volume = options.volume || 1;
  24654. this.spatialSound = options.spatialSound || false;
  24655. this.maxDistance = options.maxDistance || 100;
  24656. this.useCustomAttenuation = options.useCustomAttenation || false;
  24657. this.rolloffFactor = options.rolloffFactor || 1;
  24658. this.refDistance = options.refDistance || 1;
  24659. this.distanceModel = options.distanceModel || "linear";
  24660. this.panningModel = options.panningModel || "HRTF";
  24661. }
  24662. if (this._audioEngine.canUseWebAudio) {
  24663. this._soundGain = this._audioEngine.audioContext.createGain();
  24664. this._soundGain.gain.value = this._volume;
  24665. if (this.spatialSound) {
  24666. this._createSpatialParameters();
  24667. } else {
  24668. this._audioNode = this._soundGain;
  24669. }
  24670. this._scene.mainSoundTrack.AddSound(this);
  24671. if (typeof (urlOrArrayBuffer) === "string") {
  24672. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  24673. _this._soundLoaded(data);
  24674. }, null, null, true);
  24675. } else {
  24676. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  24677. this._soundLoaded(urlOrArrayBuffer);
  24678. } else {
  24679. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  24680. }
  24681. }
  24682. }
  24683. }
  24684. Sound.prototype._soundLoaded = function (audioData) {
  24685. var _this = this;
  24686. this._isLoaded = true;
  24687. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  24688. _this._audioBuffer = buffer;
  24689. _this._isReadyToPlay = true;
  24690. if (_this.autoplay) {
  24691. _this.play();
  24692. }
  24693. if (_this._readyToPlayCallback) {
  24694. _this._readyToPlayCallback();
  24695. }
  24696. }, function (error) {
  24697. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  24698. });
  24699. };
  24700. Sound.prototype.updateOptions = function (options) {
  24701. if (options) {
  24702. this.loop = options.loop || this.loop;
  24703. this.maxDistance = options.maxDistance || this.maxDistance;
  24704. this.useCustomAttenuation = options.useCustomAttenation || this.useCustomAttenuation;
  24705. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  24706. this.refDistance = options.refDistance || this.refDistance;
  24707. this.distanceModel = options.distanceModel || this.distanceModel;
  24708. this.panningModel = options.panningModel || this.panningModel;
  24709. }
  24710. };
  24711. Sound.prototype._createSpatialParameters = function () {
  24712. if (this._audioEngine.canUseWebAudio) {
  24713. this._soundPanner = this._audioEngine.audioContext.createPanner();
  24714. if (this.useCustomAttenuation) {
  24715. // Tricks to disable in a way embedded Web Audio attenuation
  24716. this._soundPanner.distanceModel = "linear";
  24717. this._soundPanner.maxDistance = Number.MAX_VALUE;
  24718. this._soundPanner.refDistance = 1;
  24719. this._soundPanner.rolloffFactor = 1;
  24720. this._soundPanner.panningModel = "HRTF";
  24721. } else {
  24722. this._soundPanner.distanceModel = this.distanceModel;
  24723. this._soundPanner.maxDistance = this.maxDistance;
  24724. this._soundPanner.refDistance = this.refDistance;
  24725. this._soundPanner.rolloffFactor = this.rolloffFactor;
  24726. this._soundPanner.panningModel = this.panningModel;
  24727. }
  24728. this._soundPanner.connect(this._soundGain);
  24729. this._audioNode = this._soundPanner;
  24730. }
  24731. };
  24732. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  24733. if (this._audioEngine.canUseWebAudio) {
  24734. this._audioNode.disconnect();
  24735. this._audioNode.connect(soundTrackAudioNode);
  24736. }
  24737. };
  24738. /**
  24739. * Transform this sound into a directional source
  24740. * @param coneInnerAngle Size of the inner cone in degree
  24741. * @param coneOuterAngle Size of the outer cone in degree
  24742. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  24743. */
  24744. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24745. if (coneOuterAngle < coneInnerAngle) {
  24746. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  24747. return;
  24748. }
  24749. this._coneInnerAngle = coneInnerAngle;
  24750. this._coneOuterAngle = coneOuterAngle;
  24751. this._coneOuterGain = coneOuterGain;
  24752. this._isDirectional = true;
  24753. if (this._isPlaying && this.loop) {
  24754. this.stop();
  24755. this.play();
  24756. }
  24757. };
  24758. Sound.prototype.setPosition = function (newPosition) {
  24759. this._position = newPosition;
  24760. if (this._isPlaying && this.spatialSound) {
  24761. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24762. }
  24763. };
  24764. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  24765. this._localDirection = newLocalDirection;
  24766. if (this._connectedMesh && this._isPlaying) {
  24767. this._updateDirection();
  24768. }
  24769. };
  24770. Sound.prototype._updateDirection = function () {
  24771. var mat = this._connectedMesh.getWorldMatrix();
  24772. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  24773. direction.normalize();
  24774. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  24775. };
  24776. Sound.prototype.updateDistanceFromListener = function () {
  24777. if (this._connectedMesh && this.useCustomAttenuation) {
  24778. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  24779. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  24780. }
  24781. };
  24782. Sound.prototype.setAttenuationFunction = function (callback) {
  24783. this._customAttenuationFunction = callback;
  24784. };
  24785. /**
  24786. * Play the sound
  24787. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  24788. */
  24789. Sound.prototype.play = function (time) {
  24790. if (this._isReadyToPlay) {
  24791. try {
  24792. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24793. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  24794. this._soundSource.buffer = this._audioBuffer;
  24795. if (this.spatialSound) {
  24796. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24797. if (this._isDirectional) {
  24798. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  24799. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  24800. this._soundPanner.coneOuterGain = this._coneOuterGain;
  24801. if (this._connectedMesh) {
  24802. this._updateDirection();
  24803. } else {
  24804. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  24805. }
  24806. }
  24807. }
  24808. this._soundSource.connect(this._audioNode);
  24809. this._soundSource.loop = this.loop;
  24810. this.startTime = startTime;
  24811. this._soundSource.start(startTime, this.startOffset % this._soundSource.buffer.duration);
  24812. this._isPlaying = true;
  24813. } catch (ex) {
  24814. BABYLON.Tools.Error("Error while trying to play audio: " + this._name + ", " + ex.message);
  24815. }
  24816. }
  24817. };
  24818. /**
  24819. * Stop the sound
  24820. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  24821. */
  24822. Sound.prototype.stop = function (time) {
  24823. if (this._isPlaying) {
  24824. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24825. this._soundSource.stop(stopTime);
  24826. this._isPlaying = false;
  24827. }
  24828. };
  24829. Sound.prototype.pause = function () {
  24830. if (this._isPlaying) {
  24831. this._soundSource.stop(0);
  24832. this.startOffset += this._audioEngine.audioContext.currentTime - this.startTime;
  24833. }
  24834. };
  24835. Sound.prototype.setVolume = function (newVolume) {
  24836. this._volume = newVolume;
  24837. if (this._audioEngine.canUseWebAudio) {
  24838. this._soundGain.gain.value = newVolume;
  24839. }
  24840. };
  24841. Sound.prototype.getVolume = function () {
  24842. return this._volume;
  24843. };
  24844. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  24845. var _this = this;
  24846. this._connectedMesh = meshToConnectTo;
  24847. if (!this.spatialSound) {
  24848. this._createSpatialParameters();
  24849. this.spatialSound = true;
  24850. if (this._isPlaying && this.loop) {
  24851. this.stop();
  24852. this.play();
  24853. }
  24854. }
  24855. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  24856. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  24857. });
  24858. };
  24859. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  24860. this.setPosition(connectedMesh.position);
  24861. if (this._isDirectional && this._isPlaying) {
  24862. this._updateDirection();
  24863. }
  24864. };
  24865. return Sound;
  24866. })();
  24867. BABYLON.Sound = Sound;
  24868. })(BABYLON || (BABYLON = {}));
  24869. //# sourceMappingURL=babylon.sound.js.map
  24870. var BABYLON;
  24871. (function (BABYLON) {
  24872. var SoundTrack = (function () {
  24873. function SoundTrack(scene, options) {
  24874. this.id = -1;
  24875. this._isMainTrack = false;
  24876. this._scene = scene;
  24877. this._audioEngine = scene.getEngine().getAudioEngine();
  24878. this.soundCollection = new Array();
  24879. if (this._audioEngine.canUseWebAudio) {
  24880. this._trackGain = this._audioEngine.audioContext.createGain();
  24881. //this._trackConvolver = this._audioEngine.audioContext.createConvolver();
  24882. //this._trackConvolver.connect(this._trackGain);
  24883. this._trackGain.connect(this._audioEngine.masterGain);
  24884. if (options) {
  24885. if (options.volume) {
  24886. this._trackGain.gain.value = options.volume;
  24887. }
  24888. if (options.mainTrack) {
  24889. this._isMainTrack = options.mainTrack;
  24890. }
  24891. }
  24892. }
  24893. if (!this._isMainTrack) {
  24894. this._scene.soundTracks.push(this);
  24895. this.id = this._scene.soundTracks.length - 1;
  24896. }
  24897. }
  24898. SoundTrack.prototype.AddSound = function (sound) {
  24899. sound.connectToSoundTrackAudioNode(this._trackGain);
  24900. if (sound.soundTrackId) {
  24901. if (sound.soundTrackId === -1) {
  24902. this._scene.mainSoundTrack.RemoveSound(sound);
  24903. } else {
  24904. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  24905. }
  24906. }
  24907. this.soundCollection.push(sound);
  24908. sound.soundTrackId = this.id;
  24909. };
  24910. SoundTrack.prototype.RemoveSound = function (sound) {
  24911. var index = this.soundCollection.indexOf(sound);
  24912. if (index !== -1) {
  24913. this.soundCollection.splice(index, 1);
  24914. }
  24915. };
  24916. SoundTrack.prototype.setVolume = function (newVolume) {
  24917. if (this._audioEngine.canUseWebAudio) {
  24918. this._trackGain.gain.value = newVolume;
  24919. }
  24920. };
  24921. return SoundTrack;
  24922. })();
  24923. BABYLON.SoundTrack = SoundTrack;
  24924. })(BABYLON || (BABYLON = {}));
  24925. //# sourceMappingURL=babylon.soundtrack.js.map
  24926. var BABYLON;
  24927. (function (BABYLON) {
  24928. var DebugLayer = (function () {
  24929. function DebugLayer(scene) {
  24930. var _this = this;
  24931. this._enabled = false;
  24932. this._labelsEnabled = false;
  24933. this._displayStatistics = true;
  24934. this._displayTree = false;
  24935. this._displayLogs = false;
  24936. this._identityMatrix = BABYLON.Matrix.Identity();
  24937. this.axisRatio = 0.02;
  24938. this.accentColor = "orange";
  24939. this._scene = scene;
  24940. this._syncPositions = function () {
  24941. var engine = _this._scene.getEngine();
  24942. var canvasRect = engine.getRenderingCanvasClientRect();
  24943. if (_this._showUI) {
  24944. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  24945. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  24946. _this._statsDiv.style.width = "400px";
  24947. _this._statsDiv.style.height = "auto";
  24948. _this._statsSubsetDiv.style.maxHeight = "240px";
  24949. _this._optionsDiv.style.left = "0px";
  24950. _this._optionsDiv.style.top = "10px";
  24951. _this._optionsDiv.style.width = "200px";
  24952. _this._optionsDiv.style.height = "auto";
  24953. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  24954. _this._logDiv.style.left = "0px";
  24955. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  24956. _this._logDiv.style.width = "600px";
  24957. _this._logDiv.style.height = "160px";
  24958. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  24959. _this._treeDiv.style.top = "10px";
  24960. _this._treeDiv.style.width = "300px";
  24961. _this._treeDiv.style.height = "auto";
  24962. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  24963. }
  24964. _this._globalDiv.style.left = canvasRect.left + "px";
  24965. _this._globalDiv.style.top = canvasRect.top + "px";
  24966. _this._drawingCanvas.style.left = "0px";
  24967. _this._drawingCanvas.style.top = "0px";
  24968. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  24969. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  24970. var devicePixelRatio = window.devicePixelRatio || 1;
  24971. var context = _this._drawingContext;
  24972. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  24973. _this._ratio = devicePixelRatio / backingStoreRatio;
  24974. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  24975. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  24976. };
  24977. this._onCanvasClick = function (evt) {
  24978. _this._clickPosition = {
  24979. x: evt.clientX * _this._ratio,
  24980. y: evt.clientY * _this._ratio
  24981. };
  24982. };
  24983. this._syncData = function () {
  24984. if (_this._showUI) {
  24985. if (_this._displayStatistics) {
  24986. _this._displayStats();
  24987. _this._statsDiv.style.display = "";
  24988. } else {
  24989. _this._statsDiv.style.display = "none";
  24990. }
  24991. if (_this._displayLogs) {
  24992. _this._logDiv.style.display = "";
  24993. } else {
  24994. _this._logDiv.style.display = "none";
  24995. }
  24996. if (_this._displayTree) {
  24997. _this._treeDiv.style.display = "";
  24998. if (_this._needToRefreshMeshesTree) {
  24999. _this._needToRefreshMeshesTree = false;
  25000. _this._refreshMeshesTreeContent();
  25001. }
  25002. } else {
  25003. _this._treeDiv.style.display = "none";
  25004. }
  25005. }
  25006. if (_this._labelsEnabled || !_this._showUI) {
  25007. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  25008. var engine = _this._scene.getEngine();
  25009. var viewport = _this._scene.activeCamera.viewport;
  25010. var globalViewport = viewport.toGlobal(engine);
  25011. // Meshes
  25012. var meshes = _this._scene.getActiveMeshes();
  25013. for (var index = 0; index < meshes.length; index++) {
  25014. var mesh = meshes.data[index];
  25015. var position = mesh.getBoundingInfo().boundingSphere.center;
  25016. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25017. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  25018. _this._renderAxis(projectedPosition, mesh, globalViewport);
  25019. }
  25020. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  25021. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  25022. mesh.renderOverlay = !mesh.renderOverlay;
  25023. }, function () {
  25024. return mesh.renderOverlay ? 'red' : 'black';
  25025. });
  25026. }
  25027. }
  25028. // Cameras
  25029. var cameras = _this._scene.cameras;
  25030. for (index = 0; index < cameras.length; index++) {
  25031. var camera = cameras[index];
  25032. if (camera === _this._scene.activeCamera) {
  25033. continue;
  25034. }
  25035. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25036. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  25037. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  25038. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  25039. _this._scene.activeCamera = camera;
  25040. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  25041. }, function () {
  25042. return "purple";
  25043. });
  25044. }
  25045. }
  25046. // Lights
  25047. var lights = _this._scene.lights;
  25048. for (index = 0; index < lights.length; index++) {
  25049. var light = lights[index];
  25050. if (light.position) {
  25051. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  25052. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  25053. _this._renderLabel(light.name, projectedPosition, -20, function () {
  25054. light.setEnabled(!light.isEnabled());
  25055. }, function () {
  25056. return light.isEnabled() ? "orange" : "gray";
  25057. });
  25058. }
  25059. }
  25060. }
  25061. }
  25062. _this._clickPosition = undefined;
  25063. };
  25064. }
  25065. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  25066. while (this._treeSubsetDiv.hasChildNodes()) {
  25067. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  25068. }
  25069. // Add meshes
  25070. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  25071. sortedArray.sort(function (a, b) {
  25072. if (a.name === b.name) {
  25073. return 0;
  25074. }
  25075. return (a.name > b.name) ? 1 : -1;
  25076. });
  25077. for (var index = 0; index < sortedArray.length; index++) {
  25078. var mesh = sortedArray[index];
  25079. if (!mesh.isEnabled()) {
  25080. continue;
  25081. }
  25082. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  25083. m.isVisible = element.checked;
  25084. }, mesh);
  25085. }
  25086. };
  25087. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  25088. this._drawingContext.beginPath();
  25089. this._drawingContext.moveTo(zero.x, zero.y);
  25090. this._drawingContext.lineTo(unit.x, unit.y);
  25091. this._drawingContext.strokeStyle = color;
  25092. this._drawingContext.lineWidth = 4;
  25093. this._drawingContext.stroke();
  25094. this._drawingContext.font = "normal 14px Segoe UI";
  25095. this._drawingContext.fillStyle = color;
  25096. this._drawingContext.fillText(label, unitText.x, unitText.y);
  25097. };
  25098. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  25099. var position = mesh.getBoundingInfo().boundingSphere.center;
  25100. var worldMatrix = mesh.getWorldMatrix();
  25101. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._scene.getTransformMatrix());
  25102. var unit = (unprojectedVector.subtract(position)).length();
  25103. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25104. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25105. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  25106. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25107. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25108. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  25109. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25110. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25111. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  25112. };
  25113. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  25114. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  25115. this._drawingContext.font = "normal 12px Segoe UI";
  25116. var textMetrics = this._drawingContext.measureText(text);
  25117. var centerX = projectedPosition.x - textMetrics.width / 2;
  25118. var centerY = projectedPosition.y;
  25119. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  25120. onClick();
  25121. }
  25122. this._drawingContext.beginPath();
  25123. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  25124. this._drawingContext.fillStyle = getFillStyle();
  25125. this._drawingContext.globalAlpha = 0.5;
  25126. this._drawingContext.fill();
  25127. this._drawingContext.globalAlpha = 1.0;
  25128. this._drawingContext.strokeStyle = '#FFFFFF';
  25129. this._drawingContext.lineWidth = 1;
  25130. this._drawingContext.stroke();
  25131. this._drawingContext.fillStyle = "#FFFFFF";
  25132. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  25133. this._drawingContext.beginPath();
  25134. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  25135. this._drawingContext.fill();
  25136. }
  25137. };
  25138. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  25139. if (!this._clickPosition) {
  25140. return false;
  25141. }
  25142. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  25143. return false;
  25144. }
  25145. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  25146. return false;
  25147. }
  25148. return true;
  25149. };
  25150. DebugLayer.prototype.isVisible = function () {
  25151. return this._enabled;
  25152. };
  25153. DebugLayer.prototype.hide = function () {
  25154. if (!this._enabled) {
  25155. return;
  25156. }
  25157. this._enabled = false;
  25158. var engine = this._scene.getEngine();
  25159. this._scene.unregisterAfterRender(this._syncData);
  25160. document.body.removeChild(this._globalDiv);
  25161. window.removeEventListener("resize", this._syncPositions);
  25162. this._scene.forceShowBoundingBoxes = false;
  25163. this._scene.forceWireframe = false;
  25164. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  25165. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  25166. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  25167. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  25168. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  25169. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  25170. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  25171. this._scene.shadowsEnabled = true;
  25172. this._scene.particlesEnabled = true;
  25173. this._scene.postProcessesEnabled = true;
  25174. this._scene.collisionsEnabled = true;
  25175. this._scene.lightsEnabled = true;
  25176. this._scene.texturesEnabled = true;
  25177. this._scene.lensFlaresEnabled = true;
  25178. this._scene.proceduralTexturesEnabled = true;
  25179. this._scene.renderTargetsEnabled = true;
  25180. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  25181. };
  25182. DebugLayer.prototype.show = function (showUI) {
  25183. if (typeof showUI === "undefined") { showUI = true; }
  25184. if (this._enabled) {
  25185. return;
  25186. }
  25187. this._enabled = true;
  25188. this._showUI = showUI;
  25189. var engine = this._scene.getEngine();
  25190. this._globalDiv = document.createElement("div");
  25191. document.body.appendChild(this._globalDiv);
  25192. this._generateDOMelements();
  25193. window.addEventListener("resize", this._syncPositions);
  25194. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  25195. this._syncPositions();
  25196. this._scene.registerAfterRender(this._syncData);
  25197. };
  25198. DebugLayer.prototype._clearLabels = function () {
  25199. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  25200. for (var index = 0; index < this._scene.meshes.length; index++) {
  25201. var mesh = this._scene.meshes[index];
  25202. mesh.renderOverlay = false;
  25203. }
  25204. };
  25205. DebugLayer.prototype._generateheader = function (root, text) {
  25206. var header = document.createElement("div");
  25207. header.innerHTML = text + "&nbsp;";
  25208. header.style.textAlign = "right";
  25209. header.style.width = "100%";
  25210. header.style.color = "white";
  25211. header.style.backgroundColor = "Black";
  25212. header.style.padding = "5px 5px 4px 0px";
  25213. header.style.marginLeft = "-5px";
  25214. header.style.fontWeight = "bold";
  25215. root.appendChild(header);
  25216. };
  25217. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  25218. var label = document.createElement("label");
  25219. label.innerHTML = title;
  25220. label.style.color = color;
  25221. root.appendChild(label);
  25222. root.appendChild(document.createElement("br"));
  25223. };
  25224. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  25225. if (typeof tag === "undefined") { tag = null; }
  25226. var label = document.createElement("label");
  25227. var boundingBoxesCheckbox = document.createElement("input");
  25228. boundingBoxesCheckbox.type = "checkbox";
  25229. boundingBoxesCheckbox.checked = initialState;
  25230. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  25231. task(evt.target, tag);
  25232. });
  25233. label.appendChild(boundingBoxesCheckbox);
  25234. var container = document.createElement("span");
  25235. var leftPart = document.createElement("span");
  25236. var rightPart = document.createElement("span");
  25237. rightPart.style.cssFloat = "right";
  25238. leftPart.innerHTML = leftTitle;
  25239. rightPart.innerHTML = rightTitle;
  25240. rightPart.style.fontSize = "12px";
  25241. rightPart.style.maxWidth = "200px";
  25242. container.appendChild(leftPart);
  25243. container.appendChild(rightPart);
  25244. label.appendChild(container);
  25245. root.appendChild(label);
  25246. root.appendChild(document.createElement("br"));
  25247. };
  25248. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  25249. if (typeof tag === "undefined") { tag = null; }
  25250. var label = document.createElement("label");
  25251. var boundingBoxesCheckbox = document.createElement("input");
  25252. boundingBoxesCheckbox.type = "checkbox";
  25253. boundingBoxesCheckbox.checked = initialState;
  25254. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  25255. task(evt.target, tag);
  25256. });
  25257. label.appendChild(boundingBoxesCheckbox);
  25258. label.appendChild(document.createTextNode(title));
  25259. root.appendChild(label);
  25260. root.appendChild(document.createElement("br"));
  25261. };
  25262. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  25263. if (typeof tag === "undefined") { tag = null; }
  25264. var label = document.createElement("label");
  25265. var boundingBoxesRadio = document.createElement("input");
  25266. boundingBoxesRadio.type = "radio";
  25267. boundingBoxesRadio.name = name;
  25268. boundingBoxesRadio.checked = initialState;
  25269. boundingBoxesRadio.addEventListener("change", function (evt) {
  25270. task(evt.target, tag);
  25271. });
  25272. label.appendChild(boundingBoxesRadio);
  25273. label.appendChild(document.createTextNode(title));
  25274. root.appendChild(label);
  25275. root.appendChild(document.createElement("br"));
  25276. };
  25277. DebugLayer.prototype._generateDOMelements = function () {
  25278. var _this = this;
  25279. this._globalDiv.id = "DebugLayer";
  25280. this._globalDiv.style.position = "absolute";
  25281. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  25282. this._globalDiv.style.fontSize = "14px";
  25283. this._globalDiv.style.color = "white";
  25284. // Drawing canvas
  25285. this._drawingCanvas = document.createElement("canvas");
  25286. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  25287. this._drawingCanvas.style.position = "absolute";
  25288. this._drawingCanvas.style.pointerEvents = "none";
  25289. this._drawingContext = this._drawingCanvas.getContext("2d");
  25290. this._globalDiv.appendChild(this._drawingCanvas);
  25291. if (this._showUI) {
  25292. var background = "rgba(128, 128, 128, 0.4)";
  25293. var border = "rgb(180, 180, 180) solid 1px";
  25294. // Stats
  25295. this._statsDiv = document.createElement("div");
  25296. this._statsDiv.id = "DebugLayerStats";
  25297. this._statsDiv.style.border = border;
  25298. this._statsDiv.style.position = "absolute";
  25299. this._statsDiv.style.background = background;
  25300. this._statsDiv.style.padding = "0px 0px 0px 5px";
  25301. this._generateheader(this._statsDiv, "STATISTICS");
  25302. this._statsSubsetDiv = document.createElement("div");
  25303. this._statsSubsetDiv.style.paddingTop = "5px";
  25304. this._statsSubsetDiv.style.paddingBottom = "5px";
  25305. this._statsSubsetDiv.style.overflowY = "auto";
  25306. this._statsDiv.appendChild(this._statsSubsetDiv);
  25307. // Tree
  25308. this._treeDiv = document.createElement("div");
  25309. this._treeDiv.id = "DebugLayerTree";
  25310. this._treeDiv.style.border = border;
  25311. this._treeDiv.style.position = "absolute";
  25312. this._treeDiv.style.background = background;
  25313. this._treeDiv.style.padding = "0px 0px 0px 5px";
  25314. this._treeDiv.style.display = "none";
  25315. this._generateheader(this._treeDiv, "MESHES TREE");
  25316. this._treeSubsetDiv = document.createElement("div");
  25317. this._treeSubsetDiv.style.paddingTop = "5px";
  25318. this._treeSubsetDiv.style.paddingRight = "5px";
  25319. this._treeSubsetDiv.style.overflowY = "auto";
  25320. this._treeSubsetDiv.style.maxHeight = "300px";
  25321. this._treeDiv.appendChild(this._treeSubsetDiv);
  25322. this._needToRefreshMeshesTree = true;
  25323. // Logs
  25324. this._logDiv = document.createElement("div");
  25325. this._logDiv.style.border = border;
  25326. this._logDiv.id = "DebugLayerLogs";
  25327. this._logDiv.style.position = "absolute";
  25328. this._logDiv.style.background = background;
  25329. this._logDiv.style.padding = "0px 0px 0px 5px";
  25330. this._logDiv.style.display = "none";
  25331. this._generateheader(this._logDiv, "LOGS");
  25332. this._logSubsetDiv = document.createElement("div");
  25333. this._logSubsetDiv.style.height = "127px";
  25334. this._logSubsetDiv.style.paddingTop = "5px";
  25335. this._logSubsetDiv.style.overflowY = "auto";
  25336. this._logSubsetDiv.style.fontSize = "12px";
  25337. this._logSubsetDiv.style.fontFamily = "consolas";
  25338. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  25339. this._logDiv.appendChild(this._logSubsetDiv);
  25340. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  25341. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  25342. };
  25343. // Options
  25344. this._optionsDiv = document.createElement("div");
  25345. this._optionsDiv.id = "DebugLayerOptions";
  25346. this._optionsDiv.style.border = border;
  25347. this._optionsDiv.style.position = "absolute";
  25348. this._optionsDiv.style.background = background;
  25349. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  25350. this._optionsDiv.style.overflowY = "auto";
  25351. this._generateheader(this._optionsDiv, "OPTIONS");
  25352. this._optionsSubsetDiv = document.createElement("div");
  25353. this._optionsSubsetDiv.style.paddingTop = "5px";
  25354. this._optionsSubsetDiv.style.paddingBottom = "5px";
  25355. this._optionsSubsetDiv.style.overflowY = "auto";
  25356. this._optionsSubsetDiv.style.maxHeight = "200px";
  25357. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  25358. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  25359. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  25360. _this._displayStatistics = element.checked;
  25361. });
  25362. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  25363. _this._displayLogs = element.checked;
  25364. });
  25365. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  25366. _this._displayTree = element.checked;
  25367. _this._needToRefreshMeshesTree = true;
  25368. });
  25369. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25370. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  25371. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  25372. _this._scene.forceShowBoundingBoxes = element.checked;
  25373. });
  25374. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  25375. _this._labelsEnabled = element.checked;
  25376. if (!_this._labelsEnabled) {
  25377. _this._clearLabels();
  25378. }
  25379. });
  25380. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  25381. if (element.checked) {
  25382. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  25383. } else {
  25384. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  25385. }
  25386. });
  25387. ;
  25388. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25389. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  25390. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  25391. if (element.checked) {
  25392. _this._scene.forceWireframe = false;
  25393. _this._scene.forcePointsCloud = false;
  25394. }
  25395. });
  25396. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  25397. if (element.checked) {
  25398. _this._scene.forceWireframe = true;
  25399. _this._scene.forcePointsCloud = false;
  25400. }
  25401. });
  25402. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  25403. if (element.checked) {
  25404. _this._scene.forceWireframe = false;
  25405. _this._scene.forcePointsCloud = true;
  25406. }
  25407. });
  25408. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25409. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  25410. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  25411. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  25412. });
  25413. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  25414. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  25415. });
  25416. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  25417. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  25418. });
  25419. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  25420. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  25421. });
  25422. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  25423. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  25424. });
  25425. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  25426. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  25427. });
  25428. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  25429. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  25430. });
  25431. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  25432. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  25433. });
  25434. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25435. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  25436. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  25437. _this._scene.animationsEnabled = element.checked;
  25438. });
  25439. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  25440. _this._scene.collisionsEnabled = element.checked;
  25441. });
  25442. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  25443. _this._scene.fogEnabled = element.checked;
  25444. });
  25445. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  25446. _this._scene.lensFlaresEnabled = element.checked;
  25447. });
  25448. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  25449. _this._scene.lightsEnabled = element.checked;
  25450. });
  25451. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  25452. _this._scene.particlesEnabled = element.checked;
  25453. });
  25454. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  25455. _this._scene.postProcessesEnabled = element.checked;
  25456. });
  25457. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  25458. _this._scene.proceduralTexturesEnabled = element.checked;
  25459. });
  25460. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  25461. _this._scene.renderTargetsEnabled = element.checked;
  25462. });
  25463. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  25464. _this._scene.shadowsEnabled = element.checked;
  25465. });
  25466. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  25467. _this._scene.skeletonsEnabled = element.checked;
  25468. });
  25469. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  25470. _this._scene.texturesEnabled = element.checked;
  25471. });
  25472. this._globalDiv.appendChild(this._statsDiv);
  25473. this._globalDiv.appendChild(this._logDiv);
  25474. this._globalDiv.appendChild(this._optionsDiv);
  25475. this._globalDiv.appendChild(this._treeDiv);
  25476. }
  25477. };
  25478. DebugLayer.prototype._displayStats = function () {
  25479. var scene = this._scene;
  25480. var engine = scene.getEngine();
  25481. var glInfo = engine.getGlInfo();
  25482. 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 vertices: " + scene.getActiveVertices() + "<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>";
  25483. if (this.customStatsFunction) {
  25484. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  25485. }
  25486. };
  25487. return DebugLayer;
  25488. })();
  25489. BABYLON.DebugLayer = DebugLayer;
  25490. })(BABYLON || (BABYLON = {}));
  25491. //# sourceMappingURL=babylon.debugLayer.js.map
  25492. var BABYLON;
  25493. (function (BABYLON) {
  25494. var RawTexture = (function (_super) {
  25495. __extends(RawTexture, _super);
  25496. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  25497. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25498. if (typeof invertY === "undefined") { invertY = false; }
  25499. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25500. _super.call(this, null, scene, !generateMipMaps, invertY);
  25501. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  25502. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25503. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25504. }
  25505. // Statics
  25506. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25507. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25508. if (typeof invertY === "undefined") { invertY = false; }
  25509. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25510. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  25511. };
  25512. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25513. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25514. if (typeof invertY === "undefined") { invertY = false; }
  25515. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25516. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25517. };
  25518. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25519. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25520. if (typeof invertY === "undefined") { invertY = false; }
  25521. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25522. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25523. };
  25524. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25525. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25526. if (typeof invertY === "undefined") { invertY = false; }
  25527. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25528. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  25529. };
  25530. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25531. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25532. if (typeof invertY === "undefined") { invertY = false; }
  25533. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25534. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  25535. };
  25536. return RawTexture;
  25537. })(BABYLON.Texture);
  25538. BABYLON.RawTexture = RawTexture;
  25539. })(BABYLON || (BABYLON = {}));
  25540. //# sourceMappingURL=babylon.rawTexture.js.map
  25541. var BABYLON;
  25542. (function (BABYLON) {
  25543. var IndexedVector2 = (function (_super) {
  25544. __extends(IndexedVector2, _super);
  25545. function IndexedVector2(original, index) {
  25546. _super.call(this, original.x, original.y);
  25547. this.index = index;
  25548. }
  25549. return IndexedVector2;
  25550. })(BABYLON.Vector2);
  25551. var PolygonPoints = (function () {
  25552. function PolygonPoints() {
  25553. this.elements = new Array();
  25554. }
  25555. PolygonPoints.prototype.add = function (originalPoints) {
  25556. var _this = this;
  25557. var result = new Array();
  25558. originalPoints.forEach(function (point) {
  25559. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  25560. var newPoint = new IndexedVector2(point, _this.elements.length);
  25561. result.push(newPoint);
  25562. _this.elements.push(newPoint);
  25563. }
  25564. });
  25565. return result;
  25566. };
  25567. PolygonPoints.prototype.computeBounds = function () {
  25568. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25569. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25570. this.elements.forEach(function (point) {
  25571. // x
  25572. if (point.x < lmin.x) {
  25573. lmin.x = point.x;
  25574. } else if (point.x > lmax.x) {
  25575. lmax.x = point.x;
  25576. }
  25577. // y
  25578. if (point.y < lmin.y) {
  25579. lmin.y = point.y;
  25580. } else if (point.y > lmax.y) {
  25581. lmax.y = point.y;
  25582. }
  25583. });
  25584. return {
  25585. min: lmin,
  25586. max: lmax,
  25587. width: lmax.x - lmin.x,
  25588. height: lmax.y - lmin.y
  25589. };
  25590. };
  25591. return PolygonPoints;
  25592. })();
  25593. var Polygon = (function () {
  25594. function Polygon() {
  25595. }
  25596. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  25597. return [
  25598. new BABYLON.Vector2(xmin, ymin),
  25599. new BABYLON.Vector2(xmax, ymin),
  25600. new BABYLON.Vector2(xmax, ymax),
  25601. new BABYLON.Vector2(xmin, ymax)
  25602. ];
  25603. };
  25604. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  25605. if (typeof cx === "undefined") { cx = 0; }
  25606. if (typeof cy === "undefined") { cy = 0; }
  25607. if (typeof numberOfSides === "undefined") { numberOfSides = 32; }
  25608. var result = new Array();
  25609. var angle = 0;
  25610. var increment = (Math.PI * 2) / numberOfSides;
  25611. for (var i = 0; i < numberOfSides; i++) {
  25612. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  25613. angle -= increment;
  25614. }
  25615. return result;
  25616. };
  25617. Polygon.Parse = function (input) {
  25618. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) {
  25619. return (!isNaN(val));
  25620. });
  25621. var i, result = [];
  25622. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  25623. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  25624. }
  25625. return result;
  25626. };
  25627. Polygon.StartingAt = function (x, y) {
  25628. return BABYLON.Path2.StartingAt(x, y);
  25629. };
  25630. return Polygon;
  25631. })();
  25632. BABYLON.Polygon = Polygon;
  25633. var PolygonMeshBuilder = (function () {
  25634. function PolygonMeshBuilder(name, contours, scene) {
  25635. this._points = new PolygonPoints();
  25636. if (!("poly2tri" in window)) {
  25637. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  25638. }
  25639. this._name = name;
  25640. this._scene = scene;
  25641. var points;
  25642. if (contours instanceof BABYLON.Path2) {
  25643. points = contours.getPoints();
  25644. } else {
  25645. points = contours;
  25646. }
  25647. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  25648. }
  25649. PolygonMeshBuilder.prototype.addHole = function (hole) {
  25650. this._swctx.addHole(this._points.add(hole));
  25651. return this;
  25652. };
  25653. PolygonMeshBuilder.prototype.build = function (updatable) {
  25654. if (typeof updatable === "undefined") { updatable = false; }
  25655. var result = new BABYLON.Mesh(this._name, this._scene);
  25656. var normals = [];
  25657. var positions = [];
  25658. var uvs = [];
  25659. var bounds = this._points.computeBounds();
  25660. this._points.elements.forEach(function (p) {
  25661. normals.push(0, 1.0, 0);
  25662. positions.push(p.x, 0, p.y);
  25663. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  25664. });
  25665. var indices = [];
  25666. this._swctx.triangulate();
  25667. this._swctx.getTriangles().forEach(function (triangle) {
  25668. triangle.getPoints().forEach(function (point) {
  25669. indices.push(point.index);
  25670. });
  25671. });
  25672. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  25673. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  25674. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  25675. result.setIndices(indices);
  25676. return result;
  25677. };
  25678. return PolygonMeshBuilder;
  25679. })();
  25680. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  25681. })(BABYLON || (BABYLON = {}));
  25682. //# sourceMappingURL=babylon.polygonMesh.js.map
  25683. var BABYLON;
  25684. (function (BABYLON) {
  25685. var SimplificationSettings = (function () {
  25686. function SimplificationSettings(quality, distance) {
  25687. this.quality = quality;
  25688. this.distance = distance;
  25689. }
  25690. return SimplificationSettings;
  25691. })();
  25692. BABYLON.SimplificationSettings = SimplificationSettings;
  25693. /**
  25694. * The implemented types of simplification.
  25695. * At the moment only Quadratic Error Decimation is implemented.
  25696. */
  25697. (function (SimplificationType) {
  25698. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  25699. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  25700. var SimplificationType = BABYLON.SimplificationType;
  25701. var DecimationTriangle = (function () {
  25702. function DecimationTriangle(vertices) {
  25703. this.vertices = vertices;
  25704. this.error = new Array(4);
  25705. this.deleted = false;
  25706. this.isDirty = false;
  25707. this.borderFactor = 0;
  25708. }
  25709. return DecimationTriangle;
  25710. })();
  25711. BABYLON.DecimationTriangle = DecimationTriangle;
  25712. var DecimationVertex = (function () {
  25713. function DecimationVertex(position, normal, uv, id) {
  25714. this.position = position;
  25715. this.normal = normal;
  25716. this.uv = uv;
  25717. this.id = id;
  25718. this.isBorder = true;
  25719. this.q = new QuadraticMatrix();
  25720. this.triangleCount = 0;
  25721. this.triangleStart = 0;
  25722. }
  25723. return DecimationVertex;
  25724. })();
  25725. BABYLON.DecimationVertex = DecimationVertex;
  25726. var QuadraticMatrix = (function () {
  25727. function QuadraticMatrix(data) {
  25728. this.data = new Array(10);
  25729. for (var i = 0; i < 10; ++i) {
  25730. if (data && data[i]) {
  25731. this.data[i] = data[i];
  25732. } else {
  25733. this.data[i] = 0;
  25734. }
  25735. }
  25736. }
  25737. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  25738. 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];
  25739. return det;
  25740. };
  25741. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  25742. for (var i = 0; i < 10; ++i) {
  25743. this.data[i] += matrix.data[i];
  25744. }
  25745. };
  25746. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  25747. for (var i = 0; i < 10; ++i) {
  25748. this.data[i] += data[i];
  25749. }
  25750. };
  25751. QuadraticMatrix.prototype.add = function (matrix) {
  25752. var m = new QuadraticMatrix();
  25753. for (var i = 0; i < 10; ++i) {
  25754. m.data[i] = this.data[i] + matrix.data[i];
  25755. }
  25756. return m;
  25757. };
  25758. QuadraticMatrix.FromData = function (a, b, c, d) {
  25759. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  25760. };
  25761. //returning an array to avoid garbage collection
  25762. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  25763. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  25764. };
  25765. return QuadraticMatrix;
  25766. })();
  25767. BABYLON.QuadraticMatrix = QuadraticMatrix;
  25768. var Reference = (function () {
  25769. function Reference(vertexId, triangleId) {
  25770. this.vertexId = vertexId;
  25771. this.triangleId = triangleId;
  25772. }
  25773. return Reference;
  25774. })();
  25775. BABYLON.Reference = Reference;
  25776. /**
  25777. * An implementation of the Quadratic Error simplification algorithm.
  25778. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  25779. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  25780. * @author RaananW
  25781. */
  25782. var QuadraticErrorSimplification = (function () {
  25783. function QuadraticErrorSimplification(_mesh) {
  25784. this._mesh = _mesh;
  25785. this.initialised = false;
  25786. this.syncIterations = 5000;
  25787. this.aggressiveness = 7;
  25788. this.decimationIterations = 100;
  25789. }
  25790. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  25791. var _this = this;
  25792. this.initWithMesh(this._mesh, function () {
  25793. _this.runDecimation(settings, successCallback);
  25794. });
  25795. };
  25796. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  25797. var _this = this;
  25798. var targetCount = ~~(this.triangles.length * settings.quality);
  25799. var deletedTriangles = 0;
  25800. var triangleCount = this.triangles.length;
  25801. var iterationFunction = function (iteration, callback) {
  25802. setTimeout(function () {
  25803. if (iteration % 5 === 0) {
  25804. _this.updateMesh(iteration === 0);
  25805. }
  25806. for (var i = 0; i < _this.triangles.length; ++i) {
  25807. _this.triangles[i].isDirty = false;
  25808. }
  25809. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  25810. var trianglesIterator = function (i) {
  25811. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  25812. var t = _this.triangles[tIdx];
  25813. if (!t)
  25814. return;
  25815. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  25816. return;
  25817. }
  25818. for (var j = 0; j < 3; ++j) {
  25819. if (t.error[j] < threshold) {
  25820. var deleted0 = [];
  25821. var deleted1 = [];
  25822. var i0 = t.vertices[j];
  25823. var i1 = t.vertices[(j + 1) % 3];
  25824. var v0 = _this.vertices[i0];
  25825. var v1 = _this.vertices[i1];
  25826. if (v0.isBorder !== v1.isBorder)
  25827. continue;
  25828. var p = BABYLON.Vector3.Zero();
  25829. var n = BABYLON.Vector3.Zero();
  25830. var uv = BABYLON.Vector2.Zero();
  25831. var color = new BABYLON.Color4(0, 0, 0, 1);
  25832. _this.calculateError(v0, v1, p, n, uv, color);
  25833. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor))
  25834. continue;
  25835. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor))
  25836. continue;
  25837. v0.position = p;
  25838. v0.normal = n;
  25839. if (v0.uv)
  25840. v0.uv = uv;
  25841. else if (v0.color)
  25842. v0.color = color;
  25843. v0.q = v1.q.add(v0.q);
  25844. var tStart = _this.references.length;
  25845. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  25846. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  25847. var tCount = _this.references.length - tStart;
  25848. if (tCount <= v0.triangleCount) {
  25849. if (tCount) {
  25850. for (var c = 0; c < tCount; c++) {
  25851. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  25852. }
  25853. }
  25854. } else {
  25855. v0.triangleStart = tStart;
  25856. }
  25857. v0.triangleCount = tCount;
  25858. break;
  25859. }
  25860. }
  25861. };
  25862. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  25863. return (triangleCount - deletedTriangles <= targetCount);
  25864. });
  25865. }, 0);
  25866. };
  25867. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  25868. if (triangleCount - deletedTriangles <= targetCount)
  25869. loop.breakLoop();
  25870. else {
  25871. iterationFunction(loop.index, function () {
  25872. loop.executeNext();
  25873. });
  25874. }
  25875. }, function () {
  25876. setTimeout(function () {
  25877. successCallback(_this.reconstructMesh());
  25878. }, 0);
  25879. });
  25880. };
  25881. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  25882. var _this = this;
  25883. if (!mesh)
  25884. return;
  25885. this.vertices = [];
  25886. this.triangles = [];
  25887. this._mesh = mesh;
  25888. //It is assumed that a mesh has positions, normals and either uvs or colors.
  25889. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25890. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25891. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25892. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  25893. var indices = mesh.getIndices();
  25894. var vertexInit = function (i) {
  25895. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  25896. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25897. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  25898. } else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25899. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  25900. }
  25901. _this.vertices.push(vertex);
  25902. };
  25903. var totalVertices = mesh.getTotalVertices();
  25904. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  25905. var indicesInit = function (i) {
  25906. var pos = i * 3;
  25907. var i0 = indices[pos + 0];
  25908. var i1 = indices[pos + 1];
  25909. var i2 = indices[pos + 2];
  25910. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  25911. _this.triangles.push(triangle);
  25912. };
  25913. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  25914. _this.init(callback);
  25915. });
  25916. });
  25917. };
  25918. QuadraticErrorSimplification.prototype.init = function (callback) {
  25919. var _this = this;
  25920. var triangleInit1 = function (i) {
  25921. var t = _this.triangles[i];
  25922. t.normal = BABYLON.Vector3.Cross(_this.vertices[t.vertices[1]].position.subtract(_this.vertices[t.vertices[0]].position), _this.vertices[t.vertices[2]].position.subtract(_this.vertices[t.vertices[0]].position)).normalize();
  25923. for (var j = 0; j < 3; j++) {
  25924. _this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, _this.vertices[t.vertices[0]].position))));
  25925. }
  25926. };
  25927. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  25928. var triangleInit2 = function (i) {
  25929. var t = _this.triangles[i];
  25930. for (var j = 0; j < 3; ++j) {
  25931. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  25932. }
  25933. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  25934. };
  25935. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  25936. _this.initialised = true;
  25937. callback();
  25938. });
  25939. });
  25940. };
  25941. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  25942. var newTriangles = [];
  25943. var i;
  25944. for (i = 0; i < this.vertices.length; ++i) {
  25945. this.vertices[i].triangleCount = 0;
  25946. }
  25947. var t;
  25948. var j;
  25949. for (i = 0; i < this.triangles.length; ++i) {
  25950. if (!this.triangles[i].deleted) {
  25951. t = this.triangles[i];
  25952. for (j = 0; j < 3; ++j) {
  25953. this.vertices[t.vertices[j]].triangleCount = 1;
  25954. }
  25955. newTriangles.push(t);
  25956. }
  25957. }
  25958. var newVerticesOrder = [];
  25959. //compact vertices, get the IDs of the vertices used.
  25960. var dst = 0;
  25961. for (i = 0; i < this.vertices.length; ++i) {
  25962. if (this.vertices[i].triangleCount) {
  25963. this.vertices[i].triangleStart = dst;
  25964. this.vertices[dst].position = this.vertices[i].position;
  25965. this.vertices[dst].normal = this.vertices[i].normal;
  25966. this.vertices[dst].uv = this.vertices[i].uv;
  25967. this.vertices[dst].color = this.vertices[i].color;
  25968. newVerticesOrder.push(i);
  25969. dst++;
  25970. }
  25971. }
  25972. for (i = 0; i < newTriangles.length; ++i) {
  25973. t = newTriangles[i];
  25974. for (j = 0; j < 3; ++j) {
  25975. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  25976. }
  25977. }
  25978. this.vertices = this.vertices.slice(0, dst);
  25979. var newPositionData = [];
  25980. var newNormalData = [];
  25981. var newUVsData = [];
  25982. var newColorsData = [];
  25983. for (i = 0; i < newVerticesOrder.length; ++i) {
  25984. newPositionData.push(this.vertices[i].position.x);
  25985. newPositionData.push(this.vertices[i].position.y);
  25986. newPositionData.push(this.vertices[i].position.z);
  25987. newNormalData.push(this.vertices[i].normal.x);
  25988. newNormalData.push(this.vertices[i].normal.y);
  25989. newNormalData.push(this.vertices[i].normal.z);
  25990. if (this.vertices[i].uv) {
  25991. newUVsData.push(this.vertices[i].uv.x);
  25992. newUVsData.push(this.vertices[i].uv.y);
  25993. } else if (this.vertices[i].color) {
  25994. newColorsData.push(this.vertices[i].color.r);
  25995. newColorsData.push(this.vertices[i].color.g);
  25996. newColorsData.push(this.vertices[i].color.b);
  25997. newColorsData.push(this.vertices[i].color.a);
  25998. }
  25999. }
  26000. var newIndicesArray = [];
  26001. for (i = 0; i < newTriangles.length; ++i) {
  26002. newIndicesArray.push(newTriangles[i].vertices[0]);
  26003. newIndicesArray.push(newTriangles[i].vertices[1]);
  26004. newIndicesArray.push(newTriangles[i].vertices[2]);
  26005. }
  26006. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  26007. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  26008. newMesh.material = this._mesh.material;
  26009. newMesh.parent = this._mesh.parent;
  26010. newMesh.setIndices(newIndicesArray);
  26011. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  26012. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  26013. if (newUVsData.length > 0)
  26014. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  26015. if (newColorsData.length > 0)
  26016. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  26017. //preparing the skeleton support
  26018. if (this._mesh.skeleton) {
  26019. //newMesh.skeleton = this._mesh.skeleton.clone("", "");
  26020. //newMesh.getScene().beginAnimation(newMesh.skeleton, 0, 100, true, 1.0);
  26021. }
  26022. return newMesh;
  26023. };
  26024. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor) {
  26025. for (var i = 0; i < vertex1.triangleCount; ++i) {
  26026. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  26027. if (t.deleted)
  26028. continue;
  26029. var s = this.references[vertex1.triangleStart + i].vertexId;
  26030. var id1 = t.vertices[(s + 1) % 3];
  26031. var id2 = t.vertices[(s + 2) % 3];
  26032. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  26033. deletedArray[i] = true;
  26034. continue;
  26035. }
  26036. var d1 = this.vertices[id1].position.subtract(point);
  26037. d1 = d1.normalize();
  26038. var d2 = this.vertices[id2].position.subtract(point);
  26039. d2 = d2.normalize();
  26040. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  26041. return true;
  26042. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  26043. deletedArray[i] = false;
  26044. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  26045. return true;
  26046. }
  26047. return false;
  26048. };
  26049. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  26050. var newDeleted = deletedTriangles;
  26051. for (var i = 0; i < vertex.triangleCount; ++i) {
  26052. var ref = this.references[vertex.triangleStart + i];
  26053. var t = this.triangles[ref.triangleId];
  26054. if (t.deleted)
  26055. continue;
  26056. if (deletedArray[i]) {
  26057. t.deleted = true;
  26058. newDeleted++;
  26059. continue;
  26060. }
  26061. t.vertices[ref.vertexId] = vertexId;
  26062. t.isDirty = true;
  26063. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  26064. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  26065. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  26066. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26067. this.references.push(ref);
  26068. }
  26069. return newDeleted;
  26070. };
  26071. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  26072. for (var i = 0; i < this.vertices.length; ++i) {
  26073. var vCount = [];
  26074. var vId = [];
  26075. var v = this.vertices[i];
  26076. var j;
  26077. for (j = 0; j < v.triangleCount; ++j) {
  26078. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  26079. for (var ii = 0; ii < 3; ii++) {
  26080. var ofs = 0;
  26081. var id = triangle.vertices[ii];
  26082. while (ofs < vCount.length) {
  26083. if (vId[ofs] === id)
  26084. break;
  26085. ++ofs;
  26086. }
  26087. if (ofs === vCount.length) {
  26088. vCount.push(1);
  26089. vId.push(id);
  26090. } else {
  26091. vCount[ofs]++;
  26092. }
  26093. }
  26094. }
  26095. for (j = 0; j < vCount.length; ++j) {
  26096. if (vCount[j] === 1) {
  26097. this.vertices[vId[j]].isBorder = true;
  26098. } else {
  26099. this.vertices[vId[j]].isBorder = false;
  26100. }
  26101. }
  26102. }
  26103. };
  26104. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  26105. if (typeof identifyBorders === "undefined") { identifyBorders = false; }
  26106. var i;
  26107. if (!identifyBorders) {
  26108. var newTrianglesVector = [];
  26109. for (i = 0; i < this.triangles.length; ++i) {
  26110. if (!this.triangles[i].deleted) {
  26111. newTrianglesVector.push(this.triangles[i]);
  26112. }
  26113. }
  26114. this.triangles = newTrianglesVector;
  26115. }
  26116. for (i = 0; i < this.vertices.length; ++i) {
  26117. this.vertices[i].triangleCount = 0;
  26118. this.vertices[i].triangleStart = 0;
  26119. }
  26120. var t;
  26121. var j;
  26122. var v;
  26123. for (i = 0; i < this.triangles.length; ++i) {
  26124. t = this.triangles[i];
  26125. for (j = 0; j < 3; ++j) {
  26126. v = this.vertices[t.vertices[j]];
  26127. v.triangleCount++;
  26128. }
  26129. }
  26130. var tStart = 0;
  26131. for (i = 0; i < this.vertices.length; ++i) {
  26132. this.vertices[i].triangleStart = tStart;
  26133. tStart += this.vertices[i].triangleCount;
  26134. this.vertices[i].triangleCount = 0;
  26135. }
  26136. var newReferences = new Array(this.triangles.length * 3);
  26137. for (i = 0; i < this.triangles.length; ++i) {
  26138. t = this.triangles[i];
  26139. for (j = 0; j < 3; ++j) {
  26140. v = this.vertices[t.vertices[j]];
  26141. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  26142. v.triangleCount++;
  26143. }
  26144. }
  26145. this.references = newReferences;
  26146. if (identifyBorders) {
  26147. this.identifyBorder();
  26148. }
  26149. };
  26150. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  26151. var x = point.x;
  26152. var y = point.y;
  26153. var z = point.z;
  26154. 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];
  26155. };
  26156. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  26157. var q = vertex1.q.add(vertex2.q);
  26158. var border = vertex1.isBorder && vertex2.isBorder;
  26159. var error = 0;
  26160. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  26161. if (qDet !== 0 && !border) {
  26162. if (!pointResult) {
  26163. pointResult = BABYLON.Vector3.Zero();
  26164. }
  26165. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  26166. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  26167. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  26168. error = this.vertexError(q, pointResult);
  26169. //TODO this should be correctly calculated
  26170. if (normalResult) {
  26171. normalResult.copyFrom(vertex1.normal);
  26172. if (vertex1.uv)
  26173. uvResult.copyFrom(vertex1.uv);
  26174. else if (vertex1.color)
  26175. colorResult.copyFrom(vertex1.color);
  26176. }
  26177. } else {
  26178. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  26179. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  26180. var error1 = this.vertexError(q, vertex1.position);
  26181. var error2 = this.vertexError(q, vertex2.position);
  26182. var error3 = this.vertexError(q, p3);
  26183. error = Math.min(error1, error2, error3);
  26184. if (error === error1) {
  26185. if (pointResult) {
  26186. pointResult.copyFrom(vertex1.position);
  26187. normalResult.copyFrom(vertex1.normal);
  26188. if (vertex1.uv)
  26189. uvResult.copyFrom(vertex1.uv);
  26190. else if (vertex1.color)
  26191. colorResult.copyFrom(vertex1.color);
  26192. }
  26193. } else if (error === error2) {
  26194. if (pointResult) {
  26195. pointResult.copyFrom(vertex2.position);
  26196. normalResult.copyFrom(vertex2.normal);
  26197. if (vertex2.uv)
  26198. uvResult.copyFrom(vertex2.uv);
  26199. else if (vertex2.color)
  26200. colorResult.copyFrom(vertex2.color);
  26201. }
  26202. } else {
  26203. if (pointResult) {
  26204. pointResult.copyFrom(p3);
  26205. normalResult.copyFrom(vertex1.normal);
  26206. if (vertex1.uv)
  26207. uvResult.copyFrom(vertex1.uv);
  26208. else if (vertex1.color)
  26209. colorResult.copyFrom(vertex1.color);
  26210. }
  26211. }
  26212. }
  26213. return error;
  26214. };
  26215. return QuadraticErrorSimplification;
  26216. })();
  26217. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  26218. })(BABYLON || (BABYLON = {}));
  26219. //# sourceMappingURL=babylon.meshSimplification.js.map
  26220. var BABYLON;
  26221. (function (BABYLON) {
  26222. var Analyser = (function () {
  26223. function Analyser(scene) {
  26224. this.SMOOTHING = 0.75;
  26225. this.FFT_SIZE = 512;
  26226. this.BARGRAPHAMPLITUDE = 256;
  26227. this._debugCanvasWidth = 320;
  26228. this._debugCanvasHeight = 200;
  26229. this._scene = scene;
  26230. this._audioEngine = scene.getEngine().getAudioEngine();
  26231. if (this._audioEngine.canUseWebAudio) {
  26232. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  26233. this._webAudioAnalyser.minDecibels = -140;
  26234. this._webAudioAnalyser.maxDecibels = 0;
  26235. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  26236. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  26237. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  26238. }
  26239. }
  26240. Analyser.prototype.getFrequencyBinCount = function () {
  26241. return this._webAudioAnalyser.frequencyBinCount;
  26242. };
  26243. Analyser.prototype.getByteFrequencyData = function () {
  26244. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  26245. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  26246. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  26247. return this._byteFreqs;
  26248. };
  26249. Analyser.prototype.getByteTimeDomainData = function () {
  26250. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  26251. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  26252. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  26253. return this._byteTime;
  26254. };
  26255. Analyser.prototype.getFloatFrequencyData = function () {
  26256. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  26257. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  26258. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  26259. return this._floatFreqs;
  26260. };
  26261. Analyser.prototype.drawDebugCanvas = function () {
  26262. var _this = this;
  26263. if (this._audioEngine.canUseWebAudio) {
  26264. if (!this._debugCanvas) {
  26265. this._debugCanvas = document.createElement("canvas");
  26266. this._debugCanvas.width = this._debugCanvasWidth;
  26267. this._debugCanvas.height = this._debugCanvasHeight;
  26268. this._debugCanvas.style.position = "absolute";
  26269. this._debugCanvas.style.top = "30px";
  26270. this._debugCanvas.style.left = "10px";
  26271. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  26272. document.body.appendChild(this._debugCanvas);
  26273. this._registerFunc = function () {
  26274. _this.drawDebugCanvas();
  26275. };
  26276. this._scene.registerBeforeRender(this._registerFunc);
  26277. }
  26278. if (this._registerFunc) {
  26279. var workingArray = this.getByteFrequencyData();
  26280. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  26281. this._debugCanvasContext.fillRect(0, 0, this._debugCanvasWidth, this._debugCanvasHeight);
  26282. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  26283. var value = workingArray[i];
  26284. var percent = value / this.BARGRAPHAMPLITUDE;
  26285. var height = this._debugCanvasHeight * percent;
  26286. var offset = this._debugCanvasHeight - height - 1;
  26287. var barWidth = this._debugCanvasWidth / this.getFrequencyBinCount();
  26288. var hue = i / this.getFrequencyBinCount() * 360;
  26289. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  26290. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  26291. }
  26292. }
  26293. }
  26294. };
  26295. Analyser.prototype.stopDebugCanvas = function () {
  26296. if (this._debugCanvas) {
  26297. this._scene.unregisterBeforeRender(this._registerFunc);
  26298. this._registerFunc = null;
  26299. document.body.removeChild(this._debugCanvas);
  26300. this._debugCanvas = null;
  26301. this._debugCanvasContext = null;
  26302. }
  26303. };
  26304. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  26305. if (this._audioEngine.canUseWebAudio) {
  26306. inputAudioNode.connect(this._webAudioAnalyser);
  26307. this._webAudioAnalyser.connect(outputAudioNode);
  26308. }
  26309. };
  26310. return Analyser;
  26311. })();
  26312. BABYLON.Analyser = Analyser;
  26313. })(BABYLON || (BABYLON = {}));
  26314. //# sourceMappingURL=babylon.analyser.js.map